/************************************************\
    KOC POWER - MULTILANG
    TABS
    
    VERSION: 1.1
\************************************************/

 
/************************************************************************************
*                        KOC POWER - HOMEPAGE                                        *
************************************************************************************/
Tabs.KoCScripts = {
    tabOrder : TabOptions.toKoCScripts,
    tabLabel : "KoC Scripts",
    tabDisabled : !Options.KSTab,
    myDiv : null,
    timer : null,

    init : function (div){
        var t = Tabs.KoCScripts;
        t.myDiv = div;
        t.myDiv.innerHTML  = '<CENTER><iframe src="'+homePage+'" width="950"  height="'+(Options.HauteurBoite-80)+'"  id="KsHomeFrame"></iframe><BR></center>';
    },

    hide : function (){
    },

    show : function (){
        var t = Tabs.KoCScripts;
    },
}
/************************************************************************************
*                        KOC POWER - TABS USER                                        *
************************************************************************************/
Tabs.UserTab = { //TODO rename to User
    tabOrder : TabOptions.toUserTab,
    tabLabel : Options.NewTabName,
    tabDisabled : !Options.NewTab,
    myDiv : null,
    timer : null,

    init : function (div){
        var t = Tabs.UserTab;
        t.myDiv = div;
        t.myDiv.innerHTML  = '<CENTER><iframe src="'+Options.NewTabURL+'" width="950"  height="'+(Options.HauteurBoite-30)+'"  id="KsFrame"></iframe><BR></center>';
    },

    hide : function (){
    },

    show : function (){
        var t = Tabs.UserTab;
    },
}
//TABS2


/************************************************************************************
*                        KOC POWER - TABS2 INVENTORY                                    *
************************************************************************************/
Tabs2.Stock = { //TODO rename to Inventory
    cont : null,
    init : function (){
        var t = Tabs2.Stock;
        unsafeWindow.Ksutiliser = t.useItem;
        unsafeWindow.KsutiliserAll = t.useItemAll;
        unsafeWindow.KsutiliserStop = t.useItemStop;
        t.cont = document.createElement('div');
        return t.cont;
    },
    getContent : function (){
        var t = Tabs2.Stock;
        return t.cont;
    },
    hide : function (){
        var t = Tabs2.Stock;
        t.state = null;
    },

    show : function (){
        var t = Tabs2.Stock;
        m = "<DIV class=pdxStat>"+culang.inventoryItems+"</div>";
        m += "<div style='max-height:480px; overflow-y:auto' id='KsStockContenu'></div>";
        t.cont.innerHTML = m;
        t.voir();
    },
    voir:function() {
        var t = Tabs2.Stock;
        var  category  =  ['',''+culang.mainGeneral+'',''+culang.mainSpeedups+'',''+culang.mainCombat+'',''+culang.mainRessources+'',''+culang.mainChest+'',''+culang.mainCourt+''];
        var puipui={ //item:macht,
            1300:200, 1301:1000, 1412:10, 1413:25, 1414:50, 1415:75, 1416:100, 1417:150,                 //Versorgungstruppen x1
            1310:200, 1311:1000, 1418:10, 1419:25, 1420:50, 1421:75, 1422:100, 1423:150,                 //Milizsoldaten x1
            1320:400, 1321:2000, 1424:20, 1425:50, 1426:100, 1427:150, 1428:200, 1429:300,            //Späher x2
            1330:400, 1331:2000, 1430:20, 1431:50, 1432:100, 1433:150, 1434:200, 1435:300,            //Lanzenträger x2
            1340:450, 1341:2250, 1436:30, 1437:75, 1438:150, 1439:225, 1440:300,                                 //Schwertkämpfer x3
            1350:600, 1351:3000, 1441:40, 1442:100, 1443:200, 1444:300, 1445:400,                             //Bogenschütze x4
            1360:750, 1361:3750, 1446:50, 1447:125, 1448:250, 1449:375, 1450:500,                             //Kavallerie x5
            1370:700, 1371:3500, 1451:70, 1452:175, 1453:350, 1454:525, 1455:1050,                             //Schwere Kavallerie x7
            1380:600, 1381:3000, 1456:60, 1457:150, 1458:300, 1459:450, 1460:900,                             //Versorgungswagen x6    
            1390:900, 1391:4500, 1461:90, 1462:225, 1463:450, 1464:675, 1465:1350,                             //Ballisten x9
            1400:450, 1401:1800, 1466:90, 1467:225, 1468:675, 1469:900, 1470:1350,                             //Rammbock x9    
            1410:500, 1411:2000, 1471:100, 1472:250, 1473:750, 1474:1000, 1475:1500, 1476:15000, 1477:50000,    //Steinschleudern x10    
        };
        var puitotal=0;
        var  m = "<TABLE border=0 align=center><tr><td  colspan=2><b><u>"+culang.mainArticle+"</u></b></td><td><b><u>"+culang.mainAmount+"</u></b></td><td><b><u>"+culang.mainCategory+"</u></b></td><td><b><u>"+uW.g_js_strings.commonstr.might+"</u></b></td><td>&nbsp;</td></tr>";
        var test = Seed.items;
        var e=unsafeWindow.Object.keys(Seed.items);
        var lestock = [];
        for(var d=0;d<e.length;d++) {
            var h=e[d].split("i")[1];
            var pui=0;
            if(unsafeWindow.itemlist["i"+h] && parseInt(Seed.items[e[d]])>0){
                if ((parseInt(h)<1100 || parseInt(h)>1199) && parseInt(unsafeWindow.itemlist["i"+h].category)>0) {
                    if (puipui[h])
                        pui=puipui[h] * parseInt(Seed.items[e[d]]);
                    m  += "<tr><td style='cursor: pointer;'><img  title='"+culang.inventoryUseItems+"  "+unsafeWindow.itemlist["i"+h].name+" "+culang.inventoryUseItems2+"'  id='Ksitem"+h+"' onclick='Ksutiliser("+h+");'  src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+  h + ".jpg'  width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+addCommas(Seed.items[e[d]])+"</td><td>"+  category[unsafeWindow.itemlist["i"+h].category] + "</td>";
                    if (t.timer != null) {
                        if (Options.inventory.item == h) {
                            m+="<td>"+addCommas(pui)+"</td><td><input  type='submit' value='STOP'  onclick='KsutiliserStop("+h+");'></td></tr>";
                        } else {
                            m+="<td>"+addCommas(pui)+"</td><td>&nbsp;</td></tr>";
                        }
                    } else {
                        m+="<td>"+addCommas(pui)+"</td><td><input  type='submit' value='ALL'  onclick='KsutiliserAll("+h+");'></td></tr>";
                    }
                    puitotal=puitotal+pui;
                }
            }
        }
        if (puitotal>0) {

            m+="<tr><td  colspan=4><span class=shadowCaps>"+culang.inventoryMight+"  </span></td><td><b>"+addCommas(puitotal)+"</td><td>&nbsp;</td></tr></table>";

        }
        ById('KsStockContenu').innerHTML = m;
    },
    useItem : function(num) {
        var t = Tabs2.Stock;
        unsafeWindow.cm.ItemController.use(num);
        t.voir();
    },
    timer: null,
    useItemAll : function(num) {
        var t = Tabs2.Stock;
        if (Seed.items['i'+num] > 0) {
            unsafeWindow.cm.ItemController.use(num);
            Options.inventory.active = true;
            Options.inventory.item = num;
            saveOptions();
            setTimeout(t.voir , 2000);
            t.timer = setTimeout(function() {
                t.useItemAll(num);
            }, 5000);
        } else {
            clearTimeout(t.timer);
            t.timer = null;
            Options.inventory.active = false;
            Options.inventory.item = 0;
            saveOptions();
            t.voir();
        }
    },
    useItemStop : function(num) {
        var t = Tabs2.Stock;
        clearTimeout(t.timer);
        t.timer = null;
        Options.inventory.active = false;
        Options.inventory.item = 0;
        saveOptions();
        t.voir();
    },
}
/************************************************************************************
 *                        KOC POWER - TABS2 FAKE                                        *
 ************************************************************************************/
Tabs2.Fake = {
    tabLabel : culang.tabLabelFake,
    tabDisabled : false,
    myDiv : null,
    cont : null,

    init : function (){    // called once, upon script startup
        this.myDiv = document.createElement('div');
        return this.myDiv;
    },

    hide : function (){
        var t = Tabs2.Fake;
    },
    getContent : function (){
        return Tabs2.Fake.myDiv;
    },
    show : function (){
        var t = Tabs2.Fake;
        t.cont = this.myDiv;
        var citySelect = '   <SELECT id=fakeCity>';
        for (var c=0; c<Cities.numCities; c++) {
            aCity = Cities.cities[c].name + ' ('+Cities.cities[c].x + ','+ Cities.cities[c].y+')';
            citySelect += '<option value=\''+c+'\'>'+aCity+'</option>';
        }
        citySelect += '</select>';


        var m = '<DIV class=pdxStat>Fake Angriff</div>\
            <table width="406" border="0" cellspacing="0" cellpadding="0" class="pdxTab">\
             <tr><td width="18"><img height=18  title="'+unsafeWindow.unitcost['unt1'][0]+'"  src="'+IMGmiddleSupplyTroop+'"></td><td  width="43"><INPUT type=text size=6 value=0  id=faketroop0></td><td width="18"><img height=18  title="'+unsafeWindow.unitcost['unt2'][0]+'"  src="'+IMGmiddleMilitiaman+'"></td><td  width="42"><INPUT type=text size=6 value=1  id=faketroop1></td><td width="20"><INPUT type=checkbox  id=fakeIsScout></td><td  colspan="2">'+culang.mainScoutAttack+'</td></tr>\
             <tr><td><img height=18  title="'+unsafeWindow.unitcost['unt3'][0]+'"  src="'+IMGmiddleScout+'"></td><td><INPUT type=text  size=6 value=0 id=faketroop2></td><td><img height=18  title="'+unsafeWindow.unitcost['unt4'][0]+'"  src="'+IMGmiddlePikeman+'"></td><td><INPUT type=text  size=6 value=0 id=faketroop3></td><td><INPUT  type=checkbox id=fakeIsWild></td><td  colspan="2">'+culang.mainWildAttack+'</td></tr>\
             <tr><td><img height=18  title="'+unsafeWindow.unitcost['unt5'][0]+'"  src="'+IMGmiddleSwordsman+'"></td><td><INPUT type=text  size=6 value=0 id=faketroop4></td><td><img height=18  title="'+unsafeWindow.unitcost['unt6'][0]+'"  src="'+IMGmiddleArcher+'"></td><td><INPUT type=text  size=6 value=0  id=faketroop5></td><td>&nbsp;</td><td  colspan="2">'+culang.mainIntervall+': <INPUT name="text" type=text  id=fakeSeconds value=300 size=4>'+culang.mainSeconds+'  </td></tr>\
            <tr><td><img  height=18 title="'+unsafeWindow.unitcost['unt7'][0]+'"  src="'+IMGmiddleCavalry+'"></td><td><INPUT type=text  size=6 value=0 id=faketroop6></td><td><img height=18  title="'+unsafeWindow.unitcost['unt8'][0]+'"  src="'+IMGmiddleHeavyCavalry+'"></td><td><INPUT  type=text size=6 value=0  id=faketroop7></td><td>&nbsp;</td><td  colspan="2"> '+uW.g_js_strings.commonstr.might+' <INPUT type=text  size=13 value="5441192" id=fakeMight></td></tr>\
             <tr><td><img height=18  title="'+unsafeWindow.unitcost['unt9'][0]+'"  src="'+IMGmiddleSupplyWagon+'"></td><td><INPUT  type=text size=6 value=0 id=faketroop8></td><td><img  height=18 title="'+unsafeWindow.unitcost['unt10'][0]+'"  src="'+IMGmiddleBallista+'"></td><td><INPUT type=text  size=6 value=0  id=faketroop9></td><td>&nbsp;</td><td  colspan="2">'+culang.mainName+' <INPUT type=text size=13  value="PDX" id=fakeName></td></tr>\
             <tr><td><img height=18  title="'+unsafeWindow.unitcost['unt11'][0]+'"  src="'+IMGmiddleBatteringRam+'"></td><td><INPUT  type=text size=6 value=0 id=faketroop10></td><td><img  height=18 title="'+unsafeWindow.unitcost['unt12'][0]+'"  src="'+IMGmiddleCatapult+'"></td><td><INPUT type=text  size=6 value=0  id=faketroop11></td><td>&nbsp;</td><td  width="120">'+citySelect+'</td><td width="145"><INPUT  name="submit" type=submit id=testSendMarch value="'+culang.mainAttack+'"  \></td></tr>\
            </table><INPUT  id=ptReloadKOC type=submit value="'+culang.refreshReload+'" \><DIV  id=testDiv style="background-color:#fffff0; maxwidth:675;  max-height:30px; overflow-y:auto;"></div>';

        t.cont.innerHTML = m;

        ById('testSendMarch').addEventListener ('click', t.clickFakeAttack, false);
        ById('ptReloadKOC').addEventListener ('click', t.reloadKOC, false);

        function xyNotify(city, x, y){
            var m = '[ Notified: '+ (city?city.name:'null') +', x='+ x +', y='+ y +' ]';
            ById('testNotify').innerHTML = m;
        }

    },
    writeDiv : function (msg){
        var t = Tabs2.Fake;
        if (t.state != null)
            ById('testDiv').innerHTML = msg;
    },

    addDiv : function (msg){
        var t = Tabs2.Fake;
        if (t.state != null)
            ById('testDiv').innerHTML += msg;
    },

    reloadKOC : function (){

        reloadKOC();
    },

    createFakeAttack : function (cityNum, isScout, isWild, isFalse, secs, troops, name, might){
        var marchId = 'm'+ (88888 + Math.floor(Math.random()*11111));
        var march = {};
        if (matTypeof(Seed.queue_atkinc)=='array')
            Seed.queue_atkinc = {};
        if (isFalse)
            march.marchType = 0;
        else if (isScout)
            march.marchType = 3;
        else
            march.marchType = 4;

        march.toCityId = Cities.cities[cityNum].id;
        if (isWild) {
            keys = unsafeWindow.Object.keys(Seed.wilderness['city'+Cities.cities[cityNum].id]);
            march.toTileId = Seed.wilderness['city'+Cities.cities[cityNum].id][keys[0]].tileId;
        } else {
            march.toTileId = Cities.cities[cityNum].tileId;
        }
        secs = parseInt(secs);
        march.arrivalTime = unixTime() + secs;
        march.departureTime = unixTime() - 10;
        march.unts = {}
        for(i=0; i<12; i++){
            if(troops[i] > 0)
                march.unts["u"+(i+1)] = addCommas(troops[i]);
        }
        march.pid = 1234567;
        march.score = 9;
        march.mid = marchId.substr(1);
        march.players = {}
        march.players.u1234567 = {}
        march.players.u1234567.n = name;
        march.players.u1234567.t = 60;
        march.players.u1234567.m = might;
        march.players.u1234567.s = 'M';
        march.players.u1234567.w = 1;
        march.players.u1234567.a = 1;
        march.players.u1234567.i = 5;
        Seed.queue_atkinc[marchId] = march;
        Seed.players.u1234567 = march.players.u1234567;
    },

    clickFakeAttack : function (){
        var t = Tabs2.Fake;
        var isScout = ById('fakeIsScout').checked;
        var isWild = ById('fakeIsWild').checked;
        var isFalse = false;
        var troops = [];
        for(i=0; i<12; i++)
            troops[i] = parseInt(ById('faketroop'+i).value);
        var secs = parseInt(ById('fakeSeconds').value);
        var name = ById('fakeName').value;
        var city = ById('fakeCity').value;
        var might = ById('fakeMight').value;
        t.createFakeAttack (city, isScout, isWild, isFalse, secs, troops ,name,might);
    },
}

function inspect(obj, maxLevels, level, doFunctions){
    var str = '', type, msg;
    if(level == null)  level = 0;
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)
        return 'Inspect Error: Levels number must be > 0';
    if(obj == null)
        return 'ERROR: Object is NULL\n';
    var indent = '';
    for (var i=0; i<level; i++)
        indent += '  ';
    for(property in obj) {
        //logit(property);
        try {
            type =  matTypeof(obj[property]);
            if (doFunctions==true && (type == 'function')){
                 str += indent + '(' + type + ') ' + property +  "[FUNCTION]\n   " + ( (obj[property]==null)?(': null'):('')) +' = '+  obj[property] +"\n";
            } else if (type != 'function') {
                 str += indent + '(' + type + ') ' + property + (  (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";
            }
            if((type=='object' || type=='array') && (obj[property] != null) && (level+1 < maxLevels))
                str += inspect(obj[property], maxLevels, level+1, doFunctions);  // recurse
        }
        catch(err) {
            // Is there some properties in obj we can't access? Print it red.
            if(typeof(err) == 'string') msg = err;
            else if(err.message)        msg = err.message;
            else if(err.description)    msg = err.description;
            else                        msg = ''+culang.mainUnknown+'';
            str += '(Error) ' + property + ': ' + msg +"\n";
        }
    }
    str += "\n";
    return str;
}
/************************************************************************************
 *                        KOC POWER - TABS2 ACTION LOG                                *
 ************************************************************************************/
Tabs2.ActionLog = {
    myDiv : null,
    logTab : null,
    maxEntries: 500,
    last50 : [],
    state : null,
    init : function (){    // called once, upon script startup
        this.myDiv = document.createElement('div');
        window.addEventListener('unload', t.onUnload, false);
        return this.myDiv;
    },
    show : function (div){
        var t = Tabs2.ActionLog;

        t.myDiv = this.myDiv;
         t.myDiv.innerHTML = '<DIV  class=pdxStat>'+culang.logHead+'</div><DIV  style="max-height:535px; overflow-y:auto">\
       <select id=ksLogFilter>\
       <option value="">'+culang.logSelectAll+'</option>\
       <option value="'+culang.logSelectMoreError+'">'+culang.logSelectMoreError+'</option>\
       <option value="'+culang.mainReports+'">'+culang.mainReports+'</option>\
       <option value="'+culang.mainTransport+'">'+culang.mainAutoTransport+'</option>\
       <option value="'+culang.mainSupply+'">'+culang.mainSupplyTransport+'</option>\
       <option value="'+culang.tabLabelAutoTrain+'">'+culang.tabLabelAutoTrain+'</option>\
       <option value="'+culang.mainReassign+'">'+culang.mainReassign+'</option>\
       <option value="'+culang.mainDarkForest+'">'+culang.mainDarkForest+'</option>\
       <option value="'+culang.mainRaid+'">'+culang.mainRaid+'</option>\
       <option value="'+culang.tabLabelCrest+'">'+culang.tabLabelCrest+'</option>\
       <option value="'+culang.mainGifts+'">'+culang.mainGifts+'</option>\
       <option value="'+culang.mainSpam+'">'+culang.mainSpam+'</option>\
       <option value="'+culang.tabLabelThrone+'">'+culang.tabLabelThrone+'</option>\
       <option value="'+culang.tabLabelAutoBuild+'">'+culang.tabLabelAutoBuild+'</option>\
       <option value="'+culang.mainReassign+'">'+culang.mainReassign+'</option>\
         <option value="'+culang.mainCrafting+'">' + culang.mainCrafting + '</option>\
         <option value="'+culang.mainApo+'">' + culang.mainApo + '</option>\
         <option value="'+culang.mainMarches+'">' + culang.mainMarches + '</option>\
       </select>\
        &nbsp;<input type=button value="'+culang.mainDelete+'"  id="ksLogDeleteAll"><br><TABLE cellpadding=0 cellspacing=0  id=ksActionLog  class=ksTabLined></table></div>';//15.10.2012 Bommel  added Crafting langpack reference
        t.logTab = ById('ksActionLog');
        t.filtre = ById('ksLogFilter');
        t.state = 1;
        t.filtre.addEventListener ('change', t.pouette, false);
        ById('ksLogDeleteAll').addEventListener ('click', t.deleteall, false);

        t.pouette();
    },
    deleteall: function() {
        var t = Tabs2.ActionLog;
        GM_setValue ('KsLog'+getServerId(), '[]');
        t.pouette();
    },
    pouette: function() {
        var t = Tabs2.ActionLog;
        t.logTab.innerHTML="<TR><TD></td><td></td><TD width=95%></td></tr>";
        var a = JSON2.parse(GM_getValue ('KsLog'+getServerId(), '[]'));
        if (matTypeof(a) == 'array'){
            t.last50 = a;
            for (var i=0; i<t.last50.length; i++) {
                if (t.filtre.value=="" || t.filtre.value==t.last50[i].ou) {
                    t._addTab (t.last50[i].msg, t.last50[i].ou, t.last50[i].ts);
                }

            }
        }

    },
    hide : function (){
    },
    getContent : function (){
        return Tabs2.ActionLog.myDiv;
    },
    _addTab : function (msg, ou, ts){
        var t = Tabs2.ActionLog;
        if (t.state != 1)
            return;
        if (t.logTab.rows.length >= t.maxEntries)
            t.logTab.deleteRow(t.maxEntries-1);
        var row = t.logTab.insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "<span class='logTime'>"+ts+"</span>";
        row.insertCell(1).innerHTML = "<span class='shadowCaps'>"+ou+"</span>";
        row.insertCell(2).innerHTML = "<i>"+msg+"</i>";
    },

    log : function (msg,ou){
        var t = Tabs2.ActionLog;
        var ts = new Date().toTimeString().substring (0,8);
        if (t.filtre) {
            if (t.filtre.value=="" || t.filtre.value==ou) {
                t._addTab (msg, ou, ts);
            }
        }else {
            t._addTab (msg, ou, ts);
        }
        while (t.last50.length >= 50)
            t.last50.shift();
        t.last50.push ({msg:msg, ts:ts, ou:ou});
        GM_setValue ('KsLog'+getServerId(), JSON2.stringify(t.last50));
    },
}
/************************************************************************************
*                        KOC POWER - TABS2 SPAM                                        *
************************************************************************************/
Tabs2.Spam = {
    cont : null,
    timer : null,

    init : function (){
        var t = Tabs2.Spam;
        t.cont = document.createElement('div');
        return t.cont;
    },
    getContent : function (){
        var t = Tabs2.Spam;
        return t.cont;
    },
    show : function (){
        var t = Tabs2.Spam;

         var m = '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'spamTabOptionsGlobal\').style.display=(document.getElementById(\'spamTabOptionsGlobal\').style.display==   \'none\')?\'block\':\'none\';">'+culang.spamGlobalChat+'</a></div>';
        m += '<DIV id="spamTabOptionsGlobal" style="display:none;">';
        m += '<table width="434" border="0" cellspacing="0" cellpadding="0" class="pdxTab">\
     <tr><td width="22"><INPUT id=ksSpamEnableGlobal  type=checkbox '+ (Options.spamOptions.enableGlobal?' CHECKED':'')  +'/></td><td  width="250">'+culang.mainActivate+'</td><td><b>'+culang.mainIntervall+'</b>:  <INPUT id=ksSpamMinutesGlobal type=text size=2 maxlength=3 value="'+  Options.spamOptions.spamMinGlobal +'" style="-moz-border-radius:5px;"  \> '+culang.mainMinutes+'</td></tr>\
     <tr><td colspan="3" style="text-align:center;  padding:5px;"><b>'+culang.mainMessage+'</b>: <INPUT  id=ksSpamMessageGlobal type=text size=70 maxlength=800 value="'+  Options.spamOptions.spamMessageGlobal +'" style="padding: 3px;  -moz-border-radius:5px; background-color:#FFFFFF; -moz-box-shadow: 2px  2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow:  2px 2px 2px 2px #eee; " \></td></tr>\
    </table></div>';

         m += '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'spamTabOptionsAlliance\').style.display=(document.getElementById(\'spamTabOptionsAlliance\').style.display==   \'none\')?\'block\':\'none\';">'+culang.spamAllianceChat+'</a></div>';
        m += '<DIV id="spamTabOptionsAlliance" style="display:none;">';
        m += '<table width="434" border="0" cellspacing="0" cellpadding="0" class="pdxTab">\
     <tr><td width="22"><INPUT id=ksSpamEnableAlliance  type=checkbox '+ (Options.spamOptions.enableAlliance?' CHECKED':'')  +'/></td><td width="250"  >'+culang.mainActivate+'</td><td><b>'+culang.mainIntervall+'</b>:  <INPUT id=ksSpamMinutesAlliance type=text size=2 maxlength=3  value="'+ Options.spamOptions.spamMinAlliance+'"  style="-moz-border-radius:5px;" \>  '+culang.mainMinutes+'</td></tr>\
    <tr><td  colspan="3" style="text-align:center;  padding:5px;"><b>'+culang.mainMessage+'</b>: <INPUT  id=ksSpamMessageAlliance type=text size=70 maxlength=800 value="'+  Options.spamOptions.spamMessageAlliance +'" style="padding: 3px;  -moz-border-radius:5px; background-color:#FFFFFF; -moz-box-shadow: 2px  2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow:  2px 2px 2px 2px #eee; " \></td></tr>\
    </table></div>';

        t.cont.innerHTML = m;

        ById('ksSpamEnableGlobal').addEventListener('change', function(){
            Options.spamOptions.enableGlobal = ById('ksSpamEnableGlobal').checked;
            saveOptions();
            if (Options.spamOptions.enableGlobal) SpamEvery.init();
        }, false);
        ById('ksSpamMessageGlobal').addEventListener ('change', function () {
            Options.spamOptions.spamMessageGlobal = ById('ksSpamMessageGlobal').value;
            saveOptions();
        }, false);
        ById('ksSpamMinutesGlobal').addEventListener ('change', function () {
            Options.spamOptions.spamMinGlobal = ById('ksSpamMinutesGlobal').value;
            saveOptions();
        }, false);
        ById('ksSpamEnableAlliance').addEventListener('change', function(){
            Options.spamOptions.enableAlliance = ById('ksSpamEnableAlliance').checked;
            saveOptions();            
            if (Options.spamOptions.enableAlliance) SpamEveryA.init();
        }, false);
        ById('ksSpamMessageAlliance').addEventListener ('change', function () {
            Options.spamOptions.spamMessageAlliance = ById('ksSpamMessageAlliance').value;
            saveOptions();
        }, false);
        ById('ksSpamMinutesAlliance').addEventListener ('change', function () {
            Options.spamOptions.spamMinAlliance = ById('ksSpamMinutesAlliance').value;
            saveOptions();
        }, false);

    },

    hide : function (){
        var t = Tabs2.Spam;
    },

};

/************************************************************************************
 *                        KOC POWER - TABS2 INFO                                        *
 ************************************************************************************/
Tabs2.Info = {
    cont : null,
    state : null,
    ModelCity : {},
    Trp0 : { //mm
        Life : 400,
        Atk  : 100,
        Def  : 13,
        Spd  : 200,
        Rng  : 20,
    },
    Trp1 : { //scout
        Life : 20,
        Atk  : 6,
        Def  : 1,
        Spd  : 3000,
        Rng  : 20,
    },
    Trp2 : { //pike
        Life : 600,
        Atk  : 300,
        Def  : 33,
        Spd  : 300,
        Rng  : 50,
    },
    Trp3 : { //sw
        Life : 700,
        Atk  : 200,
        Def  : 63,
        Spd  : 275,
        Rng  : 30,
    },
    Trp4 : { //arch
        Life : 500,
        Atk  : 240,
        Def  : 25,
        Spd  : 250,
        Rng  : 1200,
    },
    Trp5 : { //cav
        Life : 1000,
        Atk  : 500,
        Def  : 45,
        Spd  : 1000,
        Rng  : 100,
    },
    Trp6 : { //hc
        Life : 2000,
        Atk  : 700,
        Def  : 87,
        Spd  : 750,
        Rng  : 80,
    },
    Trp7 : { //ball
        Life : 640,
        Atk  : 900,
        Def  : 40,
        Spd  : 100,
        Rng  : 1400,
    },
    Trp8 : { //ram
        Life : 10000,
        Atk  : 500,
        Def  : 40,
        Spd  : 120,
        Rng  : 600,
    },
    Trp9 : { //cat
        Life : 960,
        Atk  : 1200,
        Def  : 50,
        Spd  : 80,
        Rng  : 1500,
    },

    Trp10 : { //blood
        Life : 2100,
        Atk  : 1300,
        Def  : 45,
        Spd  : 900,
        Rng  : 150,
    },

    Trp11 : { //exec
        Life : 4200,
        Atk  : 1700,
        Def  : 70,
        Spd  : 500,
        Rng  : 120,
    },
    
    init : function (){
        var t = Tabs2.Info;
        t.cont = document.createElement('div');
        return t.cont;
    },

    getContent : function (){
        var t = Tabs2.Info;
        return t.cont;
    },

    hide : function (){
        var t = Tabs2.Info;
    },

    show : function (){
        fortmight = {
            u53: "4",
            u55: "7",
            u60: "1",
            u61: "2",
            u62: "3",
        };
        var t = Tabs2.Info;
        rownum = 0;
        if (t.state == null){
             m = '<STYLE>.xtabH {background:#ffffe8; border:none;  padding-right: 5px; padding-left: 5px; margin-left:10px; }\
         .xtabHL { background:#ffffe8; border-width: 1px; border-style: none  none none solid; padding-right:5px; padding-left:5px; margin-left:10px;  }\
        .xtabL { background:none; border-width: 1px; border-style:  none none none solid; padding-right:5px; padding-left: 5px;  margin-left:10px; }\
        .xtabLine { padding:0px; spacing:0px;  height:1px; border-color:black; border-width: 1px; border-style: none  none solid none }</style>';

            m += '<div style="max-height:' + (Options.HauteurBoite-30) +'px;overflow-y:auto">';// OVER INFO TAB
             m += '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'infoTabExternLinks\').style.display=(document.getElementById(\'infoTabExternLinks\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadLinks+'</a></div>';
            m += '<DIV id="infoTabExternLinks" style="display:none;">';
            m += ''+culang.infoExternalLinksTable+'';
            m += '</div>';

             m += '<DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabTroopInfos\').style.display=(document.getElementById(\'infoTabTroopInfos\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadTroopInfo+'</a></div>';
            m += '<DIV id="infoTabTroopInfos" style="display:none;">';
            //Tabelle mit Truppendaten
        m +='<TABLE align=center cellpadding=1 cellspacing=0>'+
                '<TR align=center>'+
                '<TD class=xtabHL style="border-left:0;" colspan=2></td>'+
                '<TD class=xtabHL><B><u>'+culang.infoHeadTroopFoodUsage+'</u></b></td>'+
                 '<TD class=xtabHL  colspan=5><B><u>'+culang.infoHeadTroopCost+'</u></b></td>'+
                 '<TD class=xtabHL  colspan=7><B><u>'+culang.infoHeadTroopStats+'</u></B></td></tr>'+
                '<TR valign=bottom align=right>'+
                '<TD class=xtabHL style="border-left:0;" colspan=2></td>'+
                '<TD class=xtabHL>'+culang.shortFood+'</td>'+
                '<TD class=xtabHL>'+culang.shortFood+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.wood+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.stone+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.ore+'</td>'+
                '<TD class=xtabH>'+culang.overviewSPop+'</td>'+
                '<TD class=xtabHL>'+unsafeWindow.g_js_strings.commonstr.might+'</td>'+
                '<TD class=xtabH>'+culang.shortLife+'</td>'+
                '<TD class=xtabH>'+culang.shortAttack+'</td>'+
                '<TD class=xtabH>'+culang.mainSDefense+'</td>'+
                '<TD class=xtabH>'+culang.shortSpeed+'</td>'+
                '<TD class=xtabH>'+culang.mainRange+'</td>'+
                '<TD class=xtabH>'+culang.mainCharge+'</td></tr>'+
                '<TR style="height:1px;">'+
                 '<TD style="padding:0px; spacing:0px; height:1px;  border-color:black; border-width: 1px; border-style: none none solid  none" colspan=15></td></tr>';
        //Forschung
        var tch8 = Seed.tech.tch8 * 5;         //Angriff
        var tch9 = Seed.tech.tch9 * 5;         //Verteidigung
        var tch10 = Seed.tech.tch10 * 10; //Traglast
        var tch13 = Seed.tech.tch13 * 5;     //Reichweite
        var tch15 = Seed.tech.tch15 * 5;     //Leben
        //Throne
        var thr1 = uW.cm.ThroneController.effectBonus(1);     //Angriff
        var thr24 = uW.cm.ThroneController.effectBonus(24); //Infanterie-Angriff
        var thr34 = uW.cm.ThroneController.effectBonus(34); //Fernkampf-Angriff
        var thr44 = uW.cm.ThroneController.effectBonus(44); //Kavallerie-Angriff
        var thr56 = uW.cm.ThroneController.effectBonus(56); //Belagerungs-Angriff
        
        var thr2 = uW.cm.ThroneController.effectBonus(2);     //Verteidigung
        var thr25 = uW.cm.ThroneController.effectBonus(25); //Infanterie-Verteidigung
        var thr35 = uW.cm.ThroneController.effectBonus(35); //Ferkampf-Verteidigung
        var thr45 = uW.cm.ThroneController.effectBonus(45); //Kavallerie-Verteidigung

        var thr3 = uW.cm.ThroneController.effectBonus(3);     //Leben
        var thr26 = uW.cm.ThroneController.effectBonus(26); //Infanterie-Leben
        var thr36 = uW.cm.ThroneController.effectBonus(36); //Fernkampf-Leben
        var thr46 = uW.cm.ThroneController.effectBonus(46); //Kavallierie-Leben
        
        var thr4 = uW.cm.ThroneController.effectBonus(4);     //Kampftempo
        var thr27 = uW.cm.ThroneController.effectBonus(27); //Infanterie-Kampftempo
        var thr47 = uW.cm.ThroneController.effectBonus(47); //Kavallerie-Kampftempo
        var thr57 = uW.cm.ThroneController.effectBonus(57); //Belagerungs-Kampftempo
        
        var thr5 = uW.cm.ThroneController.effectBonus(5);     //Reichweite
        var thr37 = uW.cm.ThroneController.effectBonus(37); //Fernkampf-Reichweite
        var thr58 = uW.cm.ThroneController.effectBonus(58); //Belagerungs-Reichweite
        
        var thr6 = uW.cm.ThroneController.effectBonus(6);     //Traglast
        var thr48 = uW.cm.ThroneController.effectBonus(48); //Kavallerie-Traglast
        var thr59 = uW.cm.ThroneController.effectBonus(59); //Belagerungs-Traglast
        
        var thr13 = uW.cm.ThroneController.effectBonus(13); //Fallen (Angriff)
        var thr14 = uW.cm.ThroneController.effectBonus(14); //Eiserne Erdspiesse (Verteidigung, Leben)
        var thr15 = uW.cm.ThroneController.effectBonus(15); //Armbrueste (Angriff,Verteidigung,Leben,Reichweite)
        var thr16 = uW.cm.ThroneController.effectBonus(16); //Mauer (Verteidigung, Leben)
        //Truppenstats
        for (ui = 1; ui < 16; ui++) {
            if (++rownum % 2) rsty = '';
            else rsty = ' style="background: #e8e8e8" ';
            
            var cost = unsafeWindow.unitcost['unt' + ui];
            var stats = unsafeWindow.unitstats['unt' + ui];
            var food = unsafeWindow.unitupkeeps[ui];
            var might = unsafeWindow.unitmight['unt' + ui];

            var attack     = thr1;
            var defence = thr2;
            var life         = thr3;
            var speed     = thr4;
            var range        = thr5;
            var load         = thr6;
            
            var attack2 = 100 + tch8;
            var defence2= 100 + tch9;
            var life2     = 100 + tch15;
            var speed2     = 100;
            var range2    = 100 + tch13;
            var load2        = 100 + tch10;
            
            if (uW.cm.unitFrontendType[ui] == "infantry") {
                attack     += thr24;
                defence += thr25;
                life         += thr26;
                speed     += thr27;
            }
            if (uW.cm.unitFrontendType[ui] == "ranged") {
                attack     += thr34;
                defence += thr35;
                life         += thr36;
                range        += thr37;
            }
            if (uW.cm.unitFrontendType[ui] == "horsed") {
                attack     += thr44;
                defence += thr45;
                life         += thr46;
                speed     += thr47;
                load         += thr48;
            }
            if (uW.cm.unitFrontendType[ui] == "siege") {
                attack     += thr56;
                speed     += thr57;
                range        += thr58;
                if (ui != 9) load += thr59;
            }
            var attackColor = "red";
            if (attack > 800) {
                attack = 800;
                attackColor = "blue";
            }
            var defenceColor = "red";
            if (defence > 4000) {
                defence = 4000;
                defenceColor = "blue";
            }
            var lifeColor = "red";
            if (life > 200) {
                life = 200;
                lifeColor = "blue";
            }
            var speedColor = "red";
            if (speed > 300) {
                speed = 300;
                speedColor = "blue";
            }
            var rangeColor = "red";
            if (range > 150) {
                range = 150;
                rangeColor = "blue";
            }
            var loadColor = "red";
            if (load > 500) {
                load = 500;
                loadColor = "blue";
            }
            
            var attackfinal     = Math.ceil(stats[1] * (attack + attack2) / 100);
            var defencefinal     = Math.ceil(stats[2] * (defence + defence2) / 100);
            var lifefinal         = Math.ceil(stats[0] * (life + life2) / 100);
            var speedfinal         = Math.ceil(stats[3] * (speed + speed2) / 100);
            var rangefinal        = Math.ceil(stats[4] * (range + range2) / 100);
            var loadfinal         = Math.ceil(stats[5] * (load + load2) / 100);

            m +='<TR ' + rsty + 'align=right>'+
                     '<TD class=xtab rowspan=2><img  src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+ui+'_30_s34.jpg"></td>'+
                    '<TD class=xtab align=left rowspan=2><B>' + cost[0] + '</b></td>'+
                    '<TD class=xtabL rowspan=2 style="text-align:center;">' + food + '</td>'+
                    '<TD class=xtabL rowspan=2>' + addCommas(cost[1]) + '</td>'+
                    '<TD class=xtab rowspan=2>' + addCommas(cost[2]) + '</td>'+
                    '<TD class=xtab rowspan=2>' + addCommas(cost[3]) + '</td>'+
                    '<TD class=xtab rowspan=2>' + addCommas(cost[4]) + '</td>'+
                    '<TD class=xtab rowspan=2>' + addCommas(cost[6]) + '</td>'+
                    '<TD class=xtabL rowspan=2 style="text-align:center;">' + might + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[0]) + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[1]) + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[2]) + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[3]) + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[4]) + '</td>'+
                    '<TD class=xtab>' + addCommas(stats[5]) + '</td></tr>';

            m +='<TR ' + rsty + ' align=right>'+
                    '<TD class=xtab style="color:'+lifeColor+'">' + addCommas(lifefinal) + '</td>'+
                    '<TD class=xtab style="color:'+attackColor+'">' + addCommas(attackfinal) + '</td>'+
                    '<TD class=xtab style="color:'+defenceColor+'">' + addCommas(defencefinal) + '</td>'+
                    '<TD class=xtab style="color:'+speedColor+'">' + addCommas(speedfinal) + '</td>'+
                    '<TD class=xtab style="color:'+rangeColor+'">' + addCommas(rangefinal) + '</td>'+
                    '<TD class=xtab style="color:'+loadColor+'">' + addCommas(loadfinal) + '</td></tr>';
        }
    //Mauerstats
        m +='<TR style="height:1px;">'+
                 '<TD style="padding:0px; spacing:0px; height:1px;  border-color:black; border-width: 1px; border-style: none none solid  none" colspan=15></td></tr>';
        m +='<TR align=center>'+
                '<TD class=xtabHL style="border-left:0;" colspan=2></td>'+
                '<TD class=xtabHL><B><u>'+culang.infoHeadTroopFoodUsage+'</u></b></td>'+
                 '<TD class=xtabHL  colspan=5><B><u>'+culang.infoHeadTroopCost+'</u></b></td>'+
                 '<TD class=xtabHL  colspan=7><B><u>'+culang.infoHeadTroopStats+'</u></B></td></tr>'+
                '<TR valign=bottom align=right>'+
                '<TD class=xtabHL style="border-left:0;" colspan=2></td>'+
                '<TD class=xtabHL>'+culang.shortFood+'</td>'+
                '<TD class=xtabHL>'+culang.shortFood+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.wood+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.stone+'</td>'+
                '<TD class=xtabH>'+unsafeWindow.g_js_strings.commonstr.ore+'</td>'+
                '<TD class=xtabH>'+culang.overviewSPop+'</td>'+
                '<TD class=xtabHL>'+unsafeWindow.g_js_strings.commonstr.might+'</td>'+
                '<TD class=xtabH>'+culang.shortLife+'</td>'+
                '<TD class=xtabH>'+culang.shortAttack+'</td>'+
                '<TD class=xtabH>'+culang.mainSDefense+'</td>'+
                '<TD class=xtabH>'+culang.shortSpeed+'</td>'+
                '<TD class=xtabH>'+culang.mainRange+'</td>'+
                '<TD class=xtabH>'+culang.mainCharge+'</td></tr>'+
                '<TR style="height:1px;">'+
                 '<TD style="padding:0px; spacing:0px; height:1px;  border-color:black; border-width: 1px; border-style: none none solid  none" colspan=15></td></tr>';
    for (k in uW.fortcost){
      if (++rownum % 2) rsty = '';
      else rsty = ' style="background: #e8e8e8" ';
       
            var cost = uW.fortcost[k];
      var fi = k.substring(3);
      var stats = uW.fortstats['unt'+fi];
      var food = 0;
      var might = fortmight['u'+fi];
      var name = cost[0];
            
            var attack     = 100;
            var defence = 100 + thr16;
            var life         = 100 + thr16;            
            var range     = 100;
            
            //Armbrueste
            if (fi == 53) {
                attack     += thr15;
                defence += thr15;
                life         += thr15;            
                range     += thr15;
            }
            //Fallen
            if (fi == 60) {
                attack     += thr13;
            }
            //Erdspiesse
            if (fi == 62) {
                defence += thr14;
                life         += thr14;            
            }
            var attackfinal     = Math.ceil(stats[1] * attack / 100);
            var defencefinal     = Math.ceil(stats[2] * defence / 100);
            var lifefinal         = Math.ceil(stats[0] * life / 100);
            var rangefinal        = Math.ceil(stats[4] * range / 100);
                    
      m +='<TR '+ rsty +'align=right>'+
                     '<TD class=xtab rowspan=2><img  src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+fi+'_30.jpg"></td>'+
                    '<TD align=left class=xtab rowspan=2><B>'+ name +'</b></td>'+
                    '<TD class=xtabL rowspan=2 style="text-align:center;">'+ food +'</td>'+
                    '<TD class=xtabL rowspan=2>'+ addCommas(cost[1]) +'</td>'+
                    '<TD class=xtab rowspan=2>'+ addCommas(cost[2]) +'</td>'+
                    '<TD class=xtab rowspan=2>'+ addCommas(cost[3]) +'</td>'+
                    '<TD class=xtab rowspan=2>'+ addCommas(cost[4]) +'</td>'+
                    '<TD class=xtab rowspan=2>'+ addCommas(cost[6]) +'</td>'+
                    '<TD class=xtabL rowspan=2 style="text-align:center;">'+ might +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[0]) +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[1]) +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[2]) +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[3]) +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[4]) +'</td>'+
                    '<TD class=xtab>'+ addCommas(stats[5]) +'</td></tr>';
                    
            m +='<TR ' + rsty + ' align=right>'+
                    '<TD class=xtab style="color:red">' + addCommas(lifefinal) + '</td>'+
                    '<TD class=xtab style="color:red">' + addCommas(attackfinal) + '</td>'+
                    '<TD class=xtab style="color:red">' + addCommas(defencefinal) + '</td>'+
                    '<TD class=xtab style="color:red">--</td>'+
                    '<TD class=xtab style="color:red">' + addCommas(rangefinal) + '</td>'+
                    '<TD class=xtab style="color:red">--</td></tr>';
      }
      m += '<TR class=xtabLine><TD colspan=15 class=xtabLine></td></tr>';
      m += '</table>';
            m += '<div style="text-align:center;">'+culang.infoTroopHint+'</div>';
            m += '<div style="text-align:center;">'+culang.infoTroopHint2+'</div>';
            m += '</div>';
            //Ende Truppenstats
            function _displayrow (name, row){
                var tot=0;
                style = ((rownum++ % 2)?'':' style = "background: #e8e8e8"');
                m += '<TR' + style + '><TD align=right><B>' + name + '</B></td>';
                for (i=0; i<row.length; i++) {
                     m += ((row[i]==0)?'<td align=right><SPAN  class=boldRed>0</SPAN></td>':'<td  align=right>'+addCommas(parseInt(row[i]))+'</td>');
                    tot+=parseInt(row[i]);
                }
                m += '<td align=right>'+addCommas(tot)+'</td></tr>';
            }

             m += '<DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabLabor\').style.display=(document.getElementById(\'infoTabLabor\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadLabor+'</a></div>';
            m += '<DIV id="infoTabLabor" style="display:none;">';
            m += '<SPAN id="Research">&nbsp;</SPAN>';
            m += '</div>';

             m += '<DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabTrainBuildTime\').style.display=(document.getElementById(\'infoTabTrainBuildTime\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadTrainBuildTime+'</a></div>';
            m += '<DIV id="infoTabTrainBuildTime" style="display:none;">' +
                 '<TABLE align=center cellpadding=1  cellspacing=0><TABLE align=center cellpadding=1  cellspacing=0><TR align=right><TD></td>';
            infoRows = [];
            for (r=0; r<28; r++)
                infoRows[r] = [];
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                 m += "<TD align=center valign=bottom  width=60px><B>" + Cities.cities[i].name.replace(/ /g,  "<BR>").substr(0,10)  + "</B></TD>";
                var city = getTroopDefTrainEstimates(Cities.cities[i].id);
                infoRows[0][i] = city.numBarracks;
                infoRows[1][i] = city.totLevelsBarracks;
                infoRows[2][i] = city.foremanBasePoliticsScore;
                infoRows[3][i] = city.marshallCombatScore;
                infoRows[4][i] = city.stableLevel;
                infoRows[5][i] = city.workshopLevel;
                infoRows[6][i] = city.blacksmithLevel;
                for (var j=1; j<16; j++)
                    infoRows[j+6][i] = ((city['Troop'+j+'Time'] > 0)?(parseInt(36000000/city['Troop'+j+'Time'])):0);
                
                infoRows[22][i] = city['Def53Time'];
                if (infoRows[22][i] > 0)
                    infoRows[22][i] = 36000000 / infoRows[22][i];
                infoRows[23][i] = city['Def55Time'];
                if (infoRows[23][i] > 0)
                    infoRows[23][i] = 36000000 / infoRows[23][i];
                infoRows[24][i] = city['Def60Time'];
                if (infoRows[24][i] > 0)
                    infoRows[24][i] = 36000000 / infoRows[24][i];
                infoRows[25][i] = city['Def61Time'];
                if (infoRows[25][i] > 0)
                    infoRows[25][i] = 36000000 / infoRows[25][i];
                infoRows[26][i] = city['Def62Time'];
                if (infoRows[26][i] > 0)
                    infoRows[26][i] = 36000000 / infoRows[26][i];
            }
             m += "<td align=center valign=bottom width=60px><span   class='boldRed'><u>"+culang.mainTotal+"</u></span></td></tr>";
            rownum=0;
            _displayrow (culang.kocBarracks, infoRows[0]);
            _displayrow (culang.infoBarracksLvlTotal, infoRows[1]);
            _displayrow (culang.infoForemanPoints, infoRows[2]);
            _displayrow (culang.infoKnightsPoints, infoRows[3]);
            _displayrow (culang.infoStableLevel, infoRows[4]);
            _displayrow (culang.infoWorkshopLevel, infoRows[5]);
            _displayrow (culang.kocBlacksmith, infoRows[6]);

             m += "<TR><TD></TD><TD nowrap  align=center  colspan="+(Cities.numCities+1)+"><B><u>"+culang.infoTrainTroopsHour+"</u></b>  <span  class='boldRed'><sup>("+culang.infoTrainTroopsHour2+")</sup></span></TD></TR>";
             _displayrow ("<img height=18 src='"+IMGsmallSupplyTroop+"'  title='"+culang.supplytroop+"' alt='"+culang.supplytroop+"'>",  infoRows[7]);
            _displayrow ("<img height=18  src='"+IMGsmallMilitiaman+"' title='"+culang.militiaman+"'  alt='"+culang.militiaman+"'>",  infoRows[8]);
             _displayrow ("<img height=18 src='"+IMGsmallScout+"'  title='"+culang.scout+"' alt='"+culang.scout+"'>",    infoRows[9]);
             _displayrow ("<img height=18 src='"+IMGsmallPikeman+"'  title='"+culang.pikeman+"' alt='"+culang.pikeman+"'>",   infoRows[10]);
            _displayrow ("<img height=18  src='"+IMGsmallSwordsman+"' title='"+culang.swordsman+"'  alt='"+culang.swordsman+"'>",  infoRows[11]);
             _displayrow ("<img height=18 src='"+IMGsmallArcher+"'  title='"+culang.archer+"' alt='"+culang.archer+"'>",  infoRows[12]);
             _displayrow ("<img height=18 src='"+IMGsmallCavalry+"'  title='"+culang.cavalry+"' alt='"+culang.cavalry+"'>",   infoRows[13]);
            _displayrow ("<img height=18  src='"+IMGsmallHeavyCavalry+"' title='"+culang.heavycavalry+"'  alt='"+culang.heavycavalry+"'>", infoRows[14]);
             _displayrow ("<img height=18 src='"+IMGsmallSupplyWagon+"'  title='"+culang.supplywagon+"' alt='"+culang.supplywagon+"'>",  infoRows[15]);
            _displayrow ("<img height=18  src='"+IMGsmallBallista+"' title='"+culang.ballista+"'  alt='"+culang.ballista+"'>",   infoRows[16]);
             _displayrow ("<img height=18 src='"+IMGsmallBatteringRam+"'  title='"+culang.batteringram+"' alt='"+culang.batteringram+"'>",  infoRows[17]);
            _displayrow ("<img height=18  src='"+IMGsmallCatapult+"' title='"+culang.catapult+"'  alt='"+culang.catapult+"'>", infoRows[18]);
             _displayrow ("<img height=18  src='https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50_s34.jpg'  title='"+uW.unitcost['unt13'][0]+"'  alt='"+uW.unitcost['unt13'][0]+"'>", infoRows[19]);
             _displayrow ("<img height=18  src='https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50_s34.jpg'  title='"+uW.unitcost['unt14'][0]+"'  alt='"+uW.unitcost['unt14'][0]+"'>", infoRows[20]);
             _displayrow ("<img height=18  src='https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50_s34.jpg'  title='"+uW.unitcost['unt15'][0]+"'  alt='"+uW.unitcost['unt15'][0]+"'>", infoRows[21]);
            
             m += "<TR><TD></TD><TD nowrap  align=center  colspan="+(Cities.numCities+1)+"><B><u>"+culang.infoBuildDefHour+"</u></B>  <span  class='boldRed'><sup>("+culang.infoTrainTroopsHour2+")</sup></span></TD></TR>";
             _displayrow ("<img height=18 src='"+IMGmiddleCrossbows+"'  title='"+culang.crossbows+"' alt='"+culang.crossbows+"'>",  infoRows[22]);
            _displayrow ("<img height=18  src='"+IMGmiddleTrebuchet+"' title='"+culang.trebuchet+"'  alt='"+culang.trebuchet+"'>", infoRows[23]);
             _displayrow ("<img height=18 src='"+IMGmiddleTrap+"'  title='"+culang.trap+"' alt='"+culang.trap+"'>", infoRows[24]);
             _displayrow ("<img height=18 src='"+IMGmiddleCaltr+"'  title='"+culang.caltr+"' alt='"+culang.caltr+"'>", infoRows[25]);
             _displayrow ("<img height=18 src='"+IMGmiddleSpiked+"'  title='"+culang.spiked+"' alt='"+culang.spiked+"'>", infoRows[26]);
            m += "</TABLE></div>";
            
                    
             m += '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'infoTabDistanceCalc\').style.display=(document.getElementById(\'infoTabDistanceCalc\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadDistanceCalc+'</a></div>';
            m += '<DIV id="infoTabDistanceCalc" style="display:none;">';
            m += '<DIV class=pdxTab><TABLE align=center cellpadding=1 cellspacing=0>\
         <TR><TD class=xtab  align=right><B>'+culang.infoDistanceCalcStart+'  </b></td><TD title="'+culang.infoDistanceCalcNote+'"  class=xtab> X: <INPUT id=calcX type=text\> Y: <INPUT  id=calcY type=text\><SPAN  id=ptloc1></span></td></tr>\
         <TR><TD  class=xtab><B>'+culang.infoDistanceCalcTarget+'  </b></td><TD title="'+culang.infoDistanceCalcNote+'"  class=xtab> X: <INPUT id=calcX2 type=text\> Y: <INPUT  id=calcY2 type=text\><SPAN  id=ptloc2></span></td></tr></table>\
         <CENTER><DIV style="width:90%; font-size:14px;  border:  1px outset #141516; background-color:#FFFFFF;   -moz-border-radius:5px;   -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px  2px #eee;    box-shadow: 2px 2px 2px 2px #eee; margin:5px 3px 3px;  padding:4px " id=ptdistout></div>\
        <div><b>'+culang.infoDistanceCalcTroops+': </b><select id="idETASelect">\
        <option value="0" > -- '+culang.mainSelect+' -- </option>\
        <option value="1" >'+unsafeWindow.unitcost['unt1'][0]+'</option>\
        <option value="2" >'+unsafeWindow.unitcost['unt2'][0]+'</option>\
        <option value="3" >'+unsafeWindow.unitcost['unt3'][0]+'</option>\
        <option value="4" >'+unsafeWindow.unitcost['unt4'][0]+'</option>\
        <option value="5" >'+unsafeWindow.unitcost['unt5'][0]+'</option>\
        <option value="6" >'+unsafeWindow.unitcost['unt6'][0]+'</option>\
        <option value="7" >'+unsafeWindow.unitcost['unt7'][0]+'</option>\
        <option value="8" >'+unsafeWindow.unitcost['unt8'][0]+'</option>\
        <option value="9" >'+unsafeWindow.unitcost['unt9'][0]+'</option>\
        <option value="10" >'+unsafeWindow.unitcost['unt10'][0]+'</option>\
        <option value="11" >'+unsafeWindow.unitcost['unt11'][0]+'</option>\
        <option value="12" >'+unsafeWindow.unitcost['unt12'][0]+'</option>\
         </select><B> '+culang.infoDistanceCalcTroops2+'  </b></div><DIV style="width:75%; font-size:14px; border:  1px outset #141516; background-color:#FFFFFF;   -moz-border-radius:5px;   -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px  2px #eee;    box-shadow: 2px 2px 2px 2px #eee; margin:5px 0px 1px;  padding:4px" id=ptETAout </b></div>\
         <sup><span  class="boldRed">'+culang.mainImportant+'</span>:</sup>  <span  class="helpText">'+culang.infoDistanceCalcETANote+'</span>\
        </center></div></div>';
             m += '<DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabMap\').style.display=(document.getElementById(\'infoTabMap\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadMap+'</a></div>';
            m += '<DIV id="infoTabMap" style="display:none;">';
             m += '<DIV id=ptProvMap style="height:'+  provMapCoords.imgHeight +'px; width:'+ provMapCoords.imgWidth +'px;  background-repeat:no-repeat; background-image:url(\''+ URL_PROVINCE_MAP  +'\')"></div></div>';



            m +=  '<DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabThroneCaps\').style.display=(document.getElementById(\'infoTabThroneCaps\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadThroneCaps+'</a></div>';
            m += '<DIV id="infoTabThroneCaps" style="display:none;">';
            m += ''+culang.infoThroneCapsTable+'</div>';
                 m += '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'infoTabRangeCalc\').style.display=(document.getElementById(\'infoTabRangeCalc\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadRangeCalc+'</a></div>';
            m += '<DIV id="infoTabRangeCalc" style="display:none;">';
            m += '<center>'+culang.infoRangeCalcNote+'</center><br>\
                      <table><tr><td></td><td><b>'+culang.infoRangeCalcMyRange+'</b></td><td><b>'+culang.infoRangeCalcOpponent+'</b></td></tr>\
                     <tr><td>'+culang.infoRangeCalcRangeBuff+'  </td><td><input id=myrangebuff type=text  value=0></td>   <td><input id=opprangebuff type=text  value=0></td></tr>\
                     <tr><td>'+culang.infoRangeCalcRangeDebuff+'  </td><td><input id=myrangedebuff type=text  value=0></td> <td><input id=opprangedebuff type=text  value=0></td></tr>\
                     <tr><td>'+culang.infoRangeCalcSiegeBuff+'   </td><td><input id=mysiegebuff type=text  value=0></td>   <td><input id=oppsiegebuff type=text  value=0></td></tr>\
                     <tr><td>'+culang.infoRangeCalcSiegeDebuff+'  </td><td><input id=mysiegedebuff type=text  value=0></td> <td><input id=oppsiegedebuff type=text  value=0></td></tr>\
                     <tr><td>'+culang.infoRangeCalcRangedBuff+'   </td><td><input id=myrangedbuff type=text  value=0></td>  <td><input id=opprangedbuff type=text  value=0></td></tr>\
                     <tr><td>'+culang.infoRangeCalcRangedDebuff+'</td><td><input  id=myrangeddebuff type=text value=0></td><td><input  id=opprangeddebuff type=text  value=0></td></tr></table>\
                    <br><br>\
                    <span  class="boldDarkRed"><center>'+culang.infoRangeCalcNote2+'</center></span><br>\
                    '+culang.infoRangeCalcSiegeRangeDifference+' <input id=siegewinner type=text value=0><br>\
                     '+culang.infoRangeCalcRangedRangeDifference+' <input id=rangedwinner  type=text value=0></div>';            
            m +=  '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'infoTabUnitCalc\').style.display=(document.getElementById(\'infoTabUnitCalc\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadTroopCalc+'</a></div>';
            m += '<DIV id="infoTabUnitCalc" style="display:none;">\
             <DIV class=pdxStat2><a href="#"  onclick="document.getElementById(\'infoTabUnitCalcConfig\').style.display=(document.getElementById(\'infoTabUnitCalcConfig\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoHeadTroopCalcConfig+'</a></div>\
            <DIV id="infoTabUnitCalcConfig" style="display:none;">\
                             <b>Knight Combat Points</b><input id=ucKnightLevel  type=text value=50 size=4>Knight skill buffs atk,  def.<br><br>\
            <table  border=1><tr><td><b>Research</b></td><td><b>Level</b></td><td></td><td><b>Stat</b></td><td><b>Life</b></td><td><b>Atk</b></td><td><b>Def</b></td><td><b>Spd</b></td><td><b>Rng</b></td></tr>\
                             <tr><td>Healing Potions (life)   </td><td><input id=ucResHP type=text value=12  size=4></td><td></td><td>Throne  Buff</td>            <td><input id=ucLifeMod    type=text  value=0 size=4></td><td><input id=ucAtkMod     type=text value=0 size=4></td><td><input  id=ucDefMod    type=text value=0  size=4></td><td><input id=ucSpdMod    type=text  value=0 size=4></td><td><input id=ucRngMod     type=text value=0 size=4></td></tr>\
                             <tr><td>Poisoned Edge (atk)      </td><td><input id=ucResPE type=text value=12  size=4></td><td></td><td>Throne Infantry  Buff</td>   <td><input id=ucLifeModInf type=text value=0  size=4></td><td><input id=ucAtkModInf type=text  value=0 size=4></td><td><input id=ucDefModInf  type=text value=0 size=4></td><td><input  id=ucSpdModInf type=text value=0  size=4></td><td><input id=ucRngModInf type=text  value=0 size=4></td></tr>\
                             <tr><td>Metal Alloys (def)       </td><td><input id=ucResMA type=text value=12  size=4></td><td></td><td>Throne Ranged  Buff</td>     <td><input id=ucLifeModRng type=text  value=0 size=4></td><td><input id=ucAtkModRng  type=text value=0 size=4></td><td><input  id=ucDefModRng type=text value=0  size=4></td><td><input id=ucSpdModRng type=text  value=0 size=4></td><td><input id=ucRngModRng  type=text value=0 size=4></td></tr>\
                             <tr><td>Alloy Horseshoes (spd)   </td><td><input id=ucResAH type=text value=12  size=4></td><td></td><td>Throne Siege  Buff</td>      <td><input id=ucLifeModSig type=text  value=0 size=4></td><td><input id=ucAtkModSig  type=text value=0 size=4></td><td><input  id=ucDefModSig type=text value=0  size=4></td><td><input id=ucSpdModSig type=text  value=0 size=4></td><td><input id=ucRngModSig  type=text value=0 size=4></td></tr>\
                             <tr><td>Fletching (rng)          </td><td><input id=ucResFL type=text value=12  size=4></td><td></td><td>Throne Horsed  Buff</td>     <td><input id=ucLifeModHor type=text  value=0 size=4></td><td><input id=ucAtkModHor  type=text value=0 size=4></td><td><input  id=ucDefModHor type=text value=0  size=4></td><td><input id=ucSpdModHor type=text  value=0 size=4></td><td><input id=ucRngModHor  type=text value=0  size=4></td></tr></table><br>\
                            TR item caps are applied<br><br>\
             <table  border=1><tr><td><b>Guardians</b></td><td><b>Wood</b></td><td><b>Ore</b></td><td><b>Food</b></td><td><b>Stone</b></td></tr>\
                             <tr><td>Level</td>                   <td><input id=ucWood       type=text value=9  size=4></td>    <td><input id=ucOre   type=text  value=9 size=4></td><td><input id=ucFood   type=text  value=9 size=4></td><td><input id=ucStone    type=text  value=9 size=4></td></tr>\
                             <tr><td>Active</td>                  <td><input id=ucWoodAct type=radio name=ucGuard  checked></td><td><input id=ucOreAct type=radio  name=ucGuard></td><td><input id=ucFoodAct type=radio  name=ucGuard></td><td><input id=ucStoneAct type=radio  name=ucGuard></td></tr>\
                             <tr><td>Set Bonus</td><td><input  id=ucGuardSet type=checkbox  unchecked></td><td></td><td></td><td></td></tr>\
                             <tr><td>Troops on Defense (Wood  Guardian)</td><td><input id=ucDefending type=checkbox  unchecked></td><td></td><td></td><td></td></tr>\
                             <tr><td>Item Boost</td><td>+20atk<input  id=ucItemAtk20 type=checkbox  unchecked></td><td>+50atk<input id=ucItemAtk50  type=checkbox unchecked></td><td>+20def<input  id=ucItemDef20 type=checkbox  unchecked></td><td>+50def<input id=ucItemDef50  type=checkbox  unchecked></td></tr></table></div>\
             <table  border=1><tr><td><b>Unit</b></td><td><b>Life</b></td><td><b>Atk</b></td><td><b>Def</b></td><td><b>Speed</b></td><td><b>Range</b></td></tr>\
                             <tr><td>Mm      </td><td id=ucTrp0Life>  </td><td id=ucTrp0Atk> </td><td id=ucTrp0Def>  </td><td id=ucTrp0Spd> </td><td id=ucTrp0Rng>  </td></tr>\
                             <tr><td>Scout   </td><td id=ucTrp1Life>  </td><td id=ucTrp1Atk> </td><td id=ucTrp1Def>  </td><td id=ucTrp1Spd> </td><td id=ucTrp1Rng>  </td></tr>\
                             <tr><td>Pike    </td><td id=ucTrp2Life>  </td><td id=ucTrp2Atk> </td><td id=ucTrp2Def>  </td><td id=ucTrp2Spd> </td><td id=ucTrp2Rng>  </td></tr>\
                             <tr><td>Sword   </td><td id=ucTrp3Life>  </td><td id=ucTrp3Atk> </td><td id=ucTrp3Def>  </td><td id=ucTrp3Spd> </td><td id=ucTrp3Rng>  </td></tr>\
                             <tr><td>Archer  </td><td id=ucTrp4Life>  </td><td id=ucTrp4Atk> </td><td id=ucTrp4Def>  </td><td id=ucTrp4Spd> </td><td id=ucTrp4Rng>  </td></tr>\
                             <tr><td>Cav     </td><td id=ucTrp5Life>  </td><td id=ucTrp5Atk> </td><td id=ucTrp5Def>  </td><td id=ucTrp5Spd> </td><td id=ucTrp5Rng>  </td></tr>\
                             <tr><td>HC      </td><td id=ucTrp6Life>  </td><td id=ucTrp6Atk> </td><td id=ucTrp6Def>  </td><td id=ucTrp6Spd> </td><td id=ucTrp6Rng>  </td></tr>\
                             <tr><td>Ball    </td><td id=ucTrp7Life>  </td><td id=ucTrp7Atk> </td><td id=ucTrp7Def>  </td><td id=ucTrp7Spd> </td><td id=ucTrp7Rng>  </td></tr>\
                             <tr><td>Ram     </td><td id=ucTrp8Life>  </td><td id=ucTrp8Atk> </td><td id=ucTrp8Def>  </td><td id=ucTrp8Spd> </td><td id=ucTrp8Rng>  </td></tr>\
                             <tr><td>Cat     </td><td id=ucTrp9Life>  </td><td id=ucTrp9Atk> </td><td id=ucTrp9Def>  </td><td id=ucTrp9Spd> </td><td id=ucTrp9Rng>  </td></tr>\
                             <tr><td>Blood   </td><td  id=ucTrp10Life></td><td id=ucTrp10Atk></td><td  id=ucTrp10Def></td><td id=ucTrp10Spd></td><td  id=ucTrp10Rng></td></tr>\
                             <tr><td>Exec    </td><td  id=ucTrp11Life></td><td id=ucTrp11Atk></td><td  id=ucTrp11Def></td><td id=ucTrp11Spd></td><td  id=ucTrp11Rng></td></tr>\
                            </table></div>';

            
            
            
            
             m += '<DIV class=pdxStat><a href="#"  onclick="document.getElementById(\'infoTabHeadCrest\').style.display=(document.getElementById(\'infoTabHeadCrest\').style.display==   \'block\')?\'none\':\'block\';">'+culang.infoTabCrest+'</a></div>';
            m += '<DIV id="infoTabHeadCrest" style="display:none;">';
            var bor,ector,kay,bedivere,gawain,percival,galahad,lancelot,arthur,morgana,mordred;
            if (Seed.items.i1101){bor=Seed.items.i1101}else{bor=0};
            if (Seed.items.i1102){ector=Seed.items.i1102}else{ector=0};
            if (Seed.items.i1103){kay=Seed.items.i1103}else{kay=0};
            if (Seed.items.i1104){bedivere=Seed.items.i1104}else{bedivere=0};
            if (Seed.items.i1105){gawain=Seed.items.i1105}else{gawain=0};
            if (Seed.items.i1106){percival=Seed.items.i1106}else{percival=0};
            if (Seed.items.i1107){galahad=Seed.items.i1107}else{galahad=0};
            if (Seed.items.i1108){lancelot=Seed.items.i1108}else{lancelot=0};
            if (Seed.items.i1109){arthur=Seed.items.i1109}else{arthur=0};
            if (Seed.items.i1110){morgana=Seed.items.i1110}else{morgana=0};
            if (Seed.items.i1111){mordred=Seed.items.i1111}else{mordred=0};
            if (Seed.items.i1112){Stag=Seed.items.i1112}else{Stag=0};
            if (Seed.items.i1113){Pendragon=Seed.items.i1113}else{Pendragon=0};
            if (Seed.items.i1114){Lady=Seed.items.i1114}else{Lady=0};
            if (Seed.items.i1115){Merlin=Seed.items.i1115}else{Merlin=0};
            if (Seed.items.i1120){aetherseal=Seed.items.i1120}else{aetherseal=0};
            if (Seed.items.i1121){ysbadden=Seed.items.i1121}else{ysbadden=0};
            if (Cities.cities[1]){ville2="#99EE99";}else{ville2="#EE9999";}
            if (Cities.cities[2]){ville3="#99EE99";}else{ville3="#EE9999";}
            if (Cities.cities[3]){ville4="#99EE99";}else{ville4="#EE9999";}
            if (Cities.cities[4]){ville5="#99EE99";}else{ville5="#EE9999";}
            if (Cities.cities[5]){ville6="#99EE99";}else{ville6="#EE9999";}
            if (Cities.cities[6]){ville7="#99EE99";}else{ville7="#EE9999";}
            if (Cities.cities[7]){ville8="#99EE99";}else{ville8="#EE9999";}
             m += '<style>CAPTION.MYTABLE   {background-color:eeffff;color:black;border-style:solid;border-width:1px;border-color:black;}\
  TABLE.MYTABLE  { \
     font-family:arial;\
     border-collapse:collapse;\
     font-size:10pt;\
     background-color:F5F5F5;\
     width:100%;\
     border-style:solid;\
     border-color:black;\
     border-width:1px;\
  } TH.MYTABLE  {\
     font-size:10pt;\
     color:black;\
     text-align:center;\
     border-style:solid;\
     border-color:black;\
     border-width:1px;\
  } TR.MYTABLE { }\
  TD.MYTABLE {  \
     font-size:10pt;\
     background-color:FFFFE5;\
     color:black;\
     border-style:solid;\
     border-width:1px;\
     text-align:left;\
  }</style>\
<TABLE CLASS="MYTABLE" CELLPADDING=0 CELLSPACING=0>\
        <CAPTION CLASS="MYTABLE"></CAPTION><THEAD >\
        <TR CLASS="MYTABLE">\
        <TH CLASS="MYTABLE"><b><u>'+culang.mainCities+'</u></b></TH>\
        <TH CLASS="MYTABLE"><b><u>'+culang.mainRequirement+' 1</u></b></TH>\
        <TH CLASS="MYTABLE"><b><u>'+culang.mainRequirement+' 2</u></b></TH>\
        <TH CLASS="MYTABLE"><b><u>'+culang.mainRequirement+' 3</u></b></TH>\
        </TR>\
        </THEAD><TBODY>\
        <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">'+culang.mainCity+' 2</TD>\
         <TD CLASS="MYTABLE"  style="background-color:'+ville2+';">'+uW.g_js_strings.commonstr.level+'  7 ('+Seed.player.title+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">10 '+culang.mainFriends+'</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">&nbsp;</TD>\
        </TR><TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville3+';">'+culang.mainCity+' 3</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+ (  (bor>=4)?"#99EE99":ville3 ) +';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1101.jpg>&nbsp;4  '+culang.SirBors+' ('+bor+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+ (  (ector>=2)?"#99EE99":ville3 ) +';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1102.jpg>&nbsp;2  '+culang.SirEctors+'  ('+ector+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+ (  (kay>=1)?"#99EE99":ville3 ) +';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg>&nbsp;1  '+culang.SirKays+' ('+kay+')</TD>\
        </TR><TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville4+';">'+culang.mainCity+' 4</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+(  (kay>=4)?"#99EE99":ville4 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg>&nbsp;4  '+culang.SirKays+'('+kay+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (bedivere>=3)?"#99EE99":ville4 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1104.jpg>&nbsp;3  '+culang.SirBediveres+' ('+bedivere+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (gawain>=1)?"#99EE99":ville4 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1105.jpg>&nbsp;1  '+culang.SirGawains+'  ('+gawain+')</TD>\
        </TR>\
        <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville5+';">'+culang.mainCity+' 5</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+(  (percival>=4)?"#99EE99":ville5 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1106.jpg>&nbsp;4  '+culang.SirPercivals+'  ('+percival+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (galahad>=3)?"#99EE99":ville5 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1107.jpg>&nbsp;3  '+culang.SirGalahads+' ('+galahad+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (lancelot>=2)?"#99EE99":ville5 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1108.jpg>&nbsp;2  '+culang.SirLancelots+' ('+lancelot+')</TD>\
        </TR>\
        <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville6+';">'+culang.mainCity+' 6</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+(  (arthur>=4)?"#99EE99":ville6 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1109.jpg>&nbsp;4  '+culang.Arthurs+'  ('+arthur+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (morgana>=3)?"#99EE99":ville6 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1110.jpg>&nbsp;3  '+culang.Morganas+' ('+morgana+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (mordred>=2)?"#99EE99":ville6 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1111.jpg>&nbsp;2  '+culang.Mordreds+'  ('+mordred+')</TD>\
        </TR>\
        <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville7+';">'+culang.mainCity+' 7</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+(  (Stag>=4)?"#99EE99":ville7 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1112.jpg>&nbsp;4  '+culang.Stags+' ('+Stag+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (Pendragon>=3)?"#99EE99":ville7 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1113.jpg>&nbsp;3  '+culang.Pendragons+' ('+Pendragon+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (Lady>=2)?"#99EE99":ville7 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1114.jpg>&nbsp;2  '+culang.LadyoftheLake+' ('+Lady+')</TD>\
        </TR>\
        <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville8+';">'+culang.mainCity+' 8</TD>\
         <TD CLASS="MYTABLE" style="background-color:'+(  (Merlin>=4)?"#99EE99":ville8 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1115.jpg>&nbsp;4  '+culang.merlinsseal+' ('+Merlin+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (aetherseal>=3)?"#99EE99":ville8 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1120.jpg>&nbsp;3  '+culang.aetherseal+'   ('+aetherseal+')</TD>\
        <TD  CLASS="MYTABLE" style="background-color:'+(  (ysbadden>=2)?"#99EE99":ville8 )+';"><img width=25  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1121.jpg>&nbsp;2  '+culang.ysbaddenseal+'  ('+ysbadden +') </TD>\
        </TR>\
         </TBODY></TABLE><TABLE CLASS="MYTABLE"  CELLPADDING=0 CELLSPACING=0><CAPTION  CLASS="MYTABLE"><b><u>'+culang.infoCrestInventar+'</u></b></CAPTION><THEAD  >\
        <TR CLASS="MYTABLE">\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1101.jpg  title="'+culang.SirBors+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1102.jpg  title="'+culang.SirEctors+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg  title="'+culang.SirKays+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1104.jpg  title="'+culang.SirBediveres+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1105.jpg  title="'+culang.SirGawains+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1106.jpg  title="'+culang.SirPercivals+' "></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1107.jpg  title="'+culang.SirGalahads+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1108.jpg  title="'+culang.SirLancelots+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1109.jpg  title="'+culang.Arthurs+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1110.jpg  title="'+culang.Morganas+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1111.jpg  title="'+culang.Mordreds+' "></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1112.jpg  title="'+culang.Stags+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1113.jpg  title="'+culang.Pendragons+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1114.jpg  title="'+culang.LadyoftheLake+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1115.jpg  title="'+culang.merlinsseal+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1120.jpg  title="'+culang.aetherseal+'"></TH>\
        <TH  CLASS="MYTABLE"><img width=20  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1121.jpg  title="'+culang.ysbaddenseal+'"></TH>\
        </TR>\
        </THEAD><TR CLASS="MYTABLE">\
        <TD CLASS="MYTABLE"><center><b>'+bor+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+ector+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+kay+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+bedivere+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+gawain+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+percival+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+galahad+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+lancelot+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+arthur+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+morgana+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+mordred+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+Stag+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+Pendragon+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+Lady+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+Merlin+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+aetherseal+'</TD>\
        <TD CLASS="MYTABLE"><center><b>'+ysbadden+'</TD>\
        </TR><TR CLASS="MYTABLE"></tr>\
        </table></div>';
            

                    
            m += '</div>';
            
            t.cont.innerHTML = m;


            
            
             new CdispCityPicker ('ptloc1', ById('ptloc1'), true,  t.eventFromLocChanged, 0).bindToXYboxes(ById('calcX'), ById('calcY'));
             new CdispCityPicker ('ptloc2', ById('ptloc2'), true,  t.eventLocChanged, 0).bindToXYboxes(ById('calcX2'), ById('calcY2'));
            t.eventFromLocChanged(Cities.cities[0], Cities.cities[0].x, Cities.cities[0].y);
            ById('idETASelect').addEventListener ( 'change', t.eventLocChanged, false);
            function rlShow(rl) {
                 var retval = '<td width="40"><img width="40"  src="'+rl.Image+'"></td><TD  nowrap><B>'+rl.Name+'</B></TD><TD  align=right><B>&nbsp;&nbsp;';
                nlETA = ((rl.NextLevelETA > 0)?('(' + (rl.Level + 1) + ': ' + timestr(rl.NextLevelETA) + ')'):'');
                 retval += ((rl.Level < 9)?('<SPAN class=boldRed>'  + rl.Level + '</SPAN></B></TD><TD  nowrap>&nbsp;&nbsp;' + nlETA + '</TD>'):(rl.Level +  '</B></TD><TD nowrap>&nbsp;&nbsp;' + nlETA +  '</TD>'));
                return retval;
            };
            var m = '';
            getResearchLevels();
            getResearchLevels2();
            m += '<TABLE align=center cellpadding=1 cellspacing=0>' +
                 '<TR>' + rlShow(researchLevels[1]) + '<TD  width=10></TD>' + rlShow(researchLevels[6]) + '<TD  width=10></TD>' + rlShow(researchLevels[12]) + '</TR>' +
                 '<TR>' + rlShow(researchLevels[2]) +  '<TD></TD>' + rlShow(researchLevels[8]) +  '<TD></TD>' + rlShow(researchLevels[13]) + '</TR>' +
                 '<TR>' + rlShow(researchLevels[3]) +  '<TD></TD>' + rlShow(researchLevels[9]) +  '<TD></TD>' + rlShow(researchLevels[14]) + '</TR>' +
                 '<TR>' + rlShow(researchLevels[4]) +  '<TD></TD>' + rlShow(researchLevels[15]) +  '<TD></TD>' + rlShow(researchLevels[10]) + '</TR>' +
                 '<TR>' + rlShow(researchLevels[5]) +  '<TD></TD>' + rlShow(researchLevels[11]) +  '<TD></TD>' + rlShow(researchLevels[16]) + '</TR>' +
                '<TR>' + rlShow(researchLevels[17]) + '<TD colspan="10"></TD></tr>' +
                '<TR><TD colspan="14">&nbsp;</TD></tr>' +
                 '<TR>' + rlShow(researchLevels2[1]) +  '<TD></TD>' + rlShow(researchLevels2[2]) +  '<TD></TD>' + rlShow(researchLevels2[3]) + '</TR>' +
                 '<TR>' + rlShow(researchLevels2[4]) +  '<TD></TD>' + rlShow(researchLevels2[5]) +  '<TD></TD>' + rlShow(researchLevels2[6]) + '</TR>' +
                '</TABLE>';
            ById('Research').innerHTML = m;
            for (var c=0; c<Cities.numCities; c++)
                t.makeCityImg (c, ById('ptProvMap'));
            //t.state = 1;
        }
        
        
                            // Event listener Knight Level
        ById('ucKnightLevel').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        // Event listener Guardian
        ById('ucWood').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.vale > 11 ) alert('Enter a number between 0-11!');
            t.modifyUnitResearch();
        }, false);
        ById('ucOre').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.vale > 11 ) alert('Enter a number between 0-11!');
            t.modifyUnitResearch();
        }, false);
        ById('ucFood').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.vale > 11 ) alert('Enter a number between 0-11!');
            t.modifyUnitResearch();
        }, false);
        ById('ucStone').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.vale > 11 ) alert('Enter a number between 0-11!');
            t.modifyUnitResearch();
        }, false);
        ById('ucWoodAct').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucOreAct').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucFoodAct').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucStoneAct').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucGuardSet').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucDefending').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        
        //Event listener Item Boosts
        ById('ucItemAtk20').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucItemAtk50').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucItemDef20').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
        ById('ucItemDef50').addEventListener('change', function(e){
            t.modifyUnitResearch();
        }, false);
                
        // Event listener Research Level
        ById('ucResHP').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1 || e.target.vale > 12 ) alert('Enter a number between 1-12!');
            t.modifyUnitResearch();
        }, false);
        ById('ucResPE').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1 || e.target.vale > 12 ) alert('Enter a number between 1-12!');
            t.modifyUnitResearch();
        }, false);
        ById('ucResMA').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1 || e.target.vale > 12 ) alert('Enter a number between 1-12!');
            t.modifyUnitResearch();
        }, false);
                ById('ucResAH').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1 || e.target.vale > 12 ) alert('Enter a number between 1-12!');
            t.modifyUnitResearch();
        }, false);
        ById('ucResFL').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=1 ;
            if (e.target.value < 1 || e.target.vale > 12 ) alert('Enter a number between 1-12!');
            t.modifyUnitResearch();
        }, false);

        // Event listener Throne
        ById('ucLifeMod').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucLifeModInf').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucLifeModRng').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucLifeModSig').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucLifeModHor').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        ById('ucAtkMod').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucAtkModInf').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucAtkModRng').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucAtkModSig').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucAtkModHor').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        ById('ucDefMod').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucDefModInf').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucDefModRng').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucDefModSig').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucDefModHor').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        ById('ucSpdMod').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucSpdModInf').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucSpdModRng').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucSpdModSig').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucSpdModHor').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        ById('ucRngMod').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucRngModInf').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucRngModRng').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucRngModSig').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);
        ById('ucRngModHor').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            t.modifyUnitResearch();
        }, false);

        t.loadRCOptions();

        ById('myrangebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.rb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('myrangedebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.rdb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('mysiegebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.sb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('mysiegedebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.sdb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('myrangedbuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.rrb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('myrangeddebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.rrdb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('opprangebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.orb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('opprangedebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.ordb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('oppsiegebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.osb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('oppsiegedebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.osdb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('opprangedbuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.orrb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        ById('opprangeddebuff').addEventListener('change', function(e){
            if (isNaN(e.target.value)) e.target.value=0 ;
            if (e.target.value < 0) alert('Enter positive numbers!');
            KsRange.orrdb = e.target.value;
            saveKsRange();
            t.calculate();
        }, false);
        
        t.modifyUnitResearch();
        
        
    },
    makeCityImg : function (cityNum, eMap){
        var t = Tabs2.Info;
        var city = Cities.cities[cityNum];
        var x = parseInt((provMapCoords.mapWidth * city.x) / 750);
        var y = parseInt((provMapCoords.mapHeight * city.y) / 750);
        var ce = document.createElement ('div');
        ce.style.background = 'black';
        ce.style.opacity = '1.0';
        ce.style.position='relative';
        ce.style.display='block';
        ce.style.width='14px';
        ce.style.height='16px';
        ce.style.border='1px solid #fff';
        ce.style.color = 'white';
        ce.style.textAlign = 'center';
        ce.style.top = (y+provMapCoords.topMargin-(cityNum*16)-8) +'px';
        ce.style.left = (x+provMapCoords.leftMargin-7) +'px';
        eMap.appendChild(ce);
        ce.innerHTML = (cityNum+1) +'';
    },

    eventLocChanged : function (city, x, y){
        var t = Tabs2.Info;
        var x1 = parseInt(ById('calcX').value);
        var x2 = parseInt(ById('calcX2').value);
        if (isNaN(x2))
            return;
        var y1 = parseInt(ById('calcY').value);
        var y2 = parseInt(ById('calcY2').value);
         var m = ''+culang.mainDistance+ '  <u>'+culang.mainFrom+'</u> '+ x1 +','+ y1 +'  <u>'+culang.mainTo+'</u> '+ x2 +','+ y2 +'  -  '+culang.mainArrival+': &nbsp;<span class=boldRed>'+ distance  (x1, y1, x2, y2).toFixed(2) +'</span>';
        ById('ptdistout').innerHTML = m;
        var dist = distance (x1, y1, x2, y2);
        if (t.ModelCity) m = estETA(dist, ById('idETASelect').value, t.ModelCity.id,4)
        else
            m = estETA(dist, ById('idETASelect').value, 0, 4)
        if (m != null)
             ById('ptETAout').innerHTML = "<i><span  class=boldRed>"+culang.mainAttack+"</span>  <sup>"+culang.shortETA+"</sup></i> "+m.etaStr+" |  <i><span  class=boldGreen>"+culang.mainReinforce+"</span>   <sup>"+culang.shortETA+"</i></sup> "+m.friendEtaStr;
    },
    eventFromLocChanged : function (city, x, y){
        var t = Tabs2.Info;
        t.ModelCity = city;
        var x1 = parseInt(ById('calcX').value);
        var x2 = parseInt(ById('calcX2').value);
        if (isNaN(x2))
            return;
        var y1 = parseInt(ById('calcY').value);
        var y2 = parseInt(ById('calcY2').value);
         var m = ''+culang.mainDistance+ '  <u>'+culang.mainFrom+'</u> '+ x1 +','+ y1 +'   <u>'+culang.mainTo+'</u> '+ x2 +','+ y2 +' -  '+culang.mainArrival+': &nbsp;<span class=boldRed>'+ distance  (x1, y1, x2, y2).toFixed(2) +'</span>';
        ById('ptdistout').innerHTML = m;
        var dist = distance (x1, y1, x2, y2);
        if (t.ModelCity) m = estETA(dist, ById('idETASelect').value, t.ModelCity.id,4)
        else
            m = estETA(dist, ById('idETASelect').value, 0, 4)
        if (m != null)
             ById('ptETAout').innerHTML = "<i><span  class=boldRed>"+culang.mainAttack+"</span>   <sup>"+culang.shortETA+"</sup></i> "+m.etaStr+" |  <i><span class=boldGreen>"+culang.mainReinforce+"  </span>  <sup><i>"+culang.shortETA+"</i></sup>  "+m.friendEtaStr;
    },
      modifyUnitResearch : function (){
        var t = Tabs2.Info;
        var resLife = (5 * parseInt(ById('ucResHP').value)/100);
        var resAtk  = (5 * parseInt(ById('ucResPE').value)/100);
        var resDef  = (5 * parseInt(ById('ucResMA').value)/100);
        var resSpd  = (5 * parseInt(ById('ucResAH').value)/100);
        var resRng  = (5 * parseInt(ById('ucResFL').value)/100);
        var knight = parseFloat(ById('ucKnightLevel').value)/200;
        var guardLife = t.woodGuardTable(parseInt(ById('ucWood').value));
        var guardAtk = t.oreGuardTable(parseInt(ById('ucOre').value));
        var guardLifeAct =  ById('ucWoodAct').checked ? 1 : 0;
        var guardAtkAct = ById('ucOreAct').checked ? 1 : 0;
        var guardSetAct = ById('ucGuardSet').checked ? 1 : 0;
        var defending = ById('ucDefending').checked ? 1 : 0;
        var itemAtk = 0;
        var itemDef = 0;
        
        if (ById('ucItemAtk20').checked)
            itemAtk = 0.2 + itemAtk;
        if (ById('ucItemAtk50').checked)
            itemAtk = 0.5 + itemAtk;
        if (ById('ucItemDef20').checked)
            itemDef = 0.2 + itemDef;
        if (ById('ucItemDef50').checked)
            itemDef = 0.5 + itemDef;           
            
        // calculate guardian
        if (guardSetAct) { //if you have set bonus
            if (guardLifeAct && defending) { //if your want defending troop stats
                guardLife = (guardLife/2 + guardLife) / 100;
                guardAtk = guardAtk/200;
            }
            else if (guardAtkAct) {
                guardAtk = (guardAtk/2 + guardAtk) / 100;
                if(defending)
                    guardLife = guardLife/200;
                else
                    guardLife = 0;
            }
            else {
                guardAtk = guardAtk/200;
                if(defending)
                    guardLife = guardLife/200;
                else
                    guardLife = 0;
            }
        } else { // don't have set bonus
           if (guardLifeAct && defending) {
                guardLife = guardLife / 100;
                guardAtk = 0;
            }
            else if (guardAtkAct) {
                guardAtk = guardAtk / 100;
                guardLife = 0;
            }
            else {
                guardAtk = 0;
                guardLife = 0;
            }            
        }
        
        //Trp0 - mm
         ById('ucTrp0Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp0.Life + t.Trp0.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModInf').value))/100)));
         ById('ucTrp0Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp0.Atk  + t.Trp0.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModInf' ).value))/100)));
         ById('ucTrp0Def').innerHTML  = t.round2decimals(                    (t.Trp0.Def  + t.Trp0.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModInf' ).value))/100)));
         ById('ucTrp0Spd').innerHTML  = t.round2decimals(                    (t.Trp0.Spd  + t.Trp0.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModInf' ).value))/100)));
         ById('ucTrp0Rng').innerHTML  = t.round2decimals(                    (t.Trp0.Rng  + t.Trp0.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModInf' ).value))/100)));

        //Trp1 - scout
         ById('ucTrp1Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp1.Life + t.Trp1.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModInf').value))/100)));
         ById('ucTrp1Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp1.Atk  + t.Trp1.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModInf' ).value))/100)));
         ById('ucTrp1Def').innerHTML  = t.round2decimals(                    (t.Trp1.Def  + t.Trp1.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModInf' ).value))/100)));
         ById('ucTrp1Spd').innerHTML  = t.round2decimals(                    (t.Trp1.Spd  + t.Trp1.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModInf' ).value))/100)));
         ById('ucTrp1Rng').innerHTML  = t.round2decimals(                    (t.Trp1.Rng  + t.Trp1.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModInf' ).value))/100)));

        //Trp2 - pike
         ById('ucTrp2Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp2.Life + t.Trp2.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModInf').value))/100)));
         ById('ucTrp2Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp2.Atk  + t.Trp2.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModInf' ).value))/100)));
         ById('ucTrp2Def').innerHTML  = t.round2decimals(                    (t.Trp2.Def  + t.Trp2.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModInf' ).value))/100)));
         ById('ucTrp2Spd').innerHTML  = t.round2decimals(                    (t.Trp2.Spd  + t.Trp2.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModInf' ).value))/100)));
         ById('ucTrp2Rng').innerHTML  = t.round2decimals(                    (t.Trp2.Rng  + t.Trp2.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModInf' ).value))/100)));

        //Trp3 - sw
         ById('ucTrp3Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp3.Life + t.Trp3.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModInf').value))/100)));
         ById('ucTrp3Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp3.Atk  + t.Trp3.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModInf' ).value))/100)));
         ById('ucTrp3Def').innerHTML  = t.round2decimals(                    (t.Trp3.Def  + t.Trp3.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModInf' ).value))/100)));
         ById('ucTrp3Spd').innerHTML  = t.round2decimals(                    (t.Trp3.Spd  + t.Trp3.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModInf' ).value))/100)));
         ById('ucTrp3Rng').innerHTML  = t.round2decimals(                    (t.Trp3.Rng  + t.Trp3.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModInf' ).value))/100)));

        //Trp4 - arch
         ById('ucTrp4Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp4.Life + t.Trp4.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModRng').value))/100)));
         ById('ucTrp4Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp4.Atk  + t.Trp4.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModRng' ).value))/100)));
         ById('ucTrp4Def').innerHTML  = t.round2decimals(                    (t.Trp4.Def  + t.Trp4.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModRng' ).value))/100)));
         ById('ucTrp4Spd').innerHTML  = t.round2decimals(                    (t.Trp4.Spd  + t.Trp4.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModRng' ).value))/100)));
         ById('ucTrp4Rng').innerHTML  = t.round2decimals(                    (t.Trp4.Rng  + t.Trp4.Rng  * (resRng                     +  t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModRng' ).value))/100)));

        //Trp5 - cav
         ById('ucTrp5Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp5.Life + t.Trp5.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModHor').value))/100)));
         ById('ucTrp5Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp5.Atk  + t.Trp5.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModHor' ).value))/100)));
         ById('ucTrp5Def').innerHTML  = t.round2decimals(                    (t.Trp5.Def  + t.Trp5.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModHor' ).value))/100)));
         ById('ucTrp5Spd').innerHTML  = t.round2decimals(                    (t.Trp5.Spd  + t.Trp5.Spd  * (resSpd                     +  t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModHor' ).value))/100)));
         ById('ucTrp5Rng').innerHTML  = t.round2decimals(                    (t.Trp5.Rng  + t.Trp5.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModHor' ).value))/100)));

        //Trp6 - hc
         ById('ucTrp6Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp6.Life + t.Trp6.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModHor').value))/100)));
         ById('ucTrp6Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp6.Atk  + t.Trp6.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModHor' ).value))/100)));
         ById('ucTrp6Def').innerHTML  = t.round2decimals(                    (t.Trp6.Def  + t.Trp6.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModHor' ).value))/100)));
         ById('ucTrp6Spd').innerHTML  = t.round2decimals(                    (t.Trp6.Spd  + t.Trp6.Spd  * (resSpd                     +  t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModHor' ).value))/100)));
         ById('ucTrp6Rng').innerHTML  = t.round2decimals(                    (t.Trp6.Rng  + t.Trp6.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModHor' ).value))/100)));

        //Trp7 - ball
         ById('ucTrp7Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp7.Life + t.Trp7.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModSig').value))/100)));
         ById('ucTrp7Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp7.Atk  + t.Trp7.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModSig' ).value))/100)));
         ById('ucTrp7Def').innerHTML  = t.round2decimals(                    (t.Trp7.Def  + t.Trp7.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModSig' ).value))/100)));
         ById('ucTrp7Spd').innerHTML  = t.round2decimals(                    (t.Trp7.Spd  + t.Trp7.Spd  * (resSpd                     +  t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModSig' ).value))/100)));
         ById('ucTrp7Rng').innerHTML  = t.round2decimals(                    (t.Trp7.Rng  + t.Trp7.Rng  * (resRng                     +  t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModSig' ).value))/100)));

        //Trp8 - ram
         ById('ucTrp8Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp8.Life + t.Trp8.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModSig').value))/100)));
         ById('ucTrp8Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp8.Atk  + t.Trp8.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModSig' ).value))/100)));
         ById('ucTrp8Def').innerHTML  = t.round2decimals(                    (t.Trp8.Def  + t.Trp8.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModSig' ).value))/100)));
         ById('ucTrp8Spd').innerHTML  = t.round2decimals(                    (t.Trp8.Spd  + t.Trp8.Spd  * (resSpd                     +  t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModSig' ).value))/100)));
         ById('ucTrp8Rng').innerHTML  = t.round2decimals(                    (t.Trp8.Rng  + t.Trp8.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModSig' ).value))/100)));

        //Trp9 - cat
         ById('ucTrp9Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp9.Life + t.Trp9.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),parseFloat(ById('ucLifeModSig').value))/100)));
         ById('ucTrp9Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp9.Atk  + t.Trp9.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod'  ).value),parseFloat(ById('ucAtkModSig' ).value))/100)));
         ById('ucTrp9Def').innerHTML  = t.round2decimals(                    (t.Trp9.Def  + t.Trp9.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod'  ).value),parseFloat(ById('ucDefModSig' ).value))/100)));
         ById('ucTrp9Spd').innerHTML  = t.round2decimals(                    (t.Trp9.Spd  + t.Trp9.Spd  * (resSpd                     +  t.maxBuff('spd', parseFloat(ById('ucSpdMod'  ).value),parseFloat(ById('ucSpdModSig' ).value))/100)));
         ById('ucTrp9Rng').innerHTML  = t.round2decimals(                    (t.Trp9.Rng  + t.Trp9.Rng  * (resRng                     +  t.maxBuff('rng', parseFloat(ById('ucRngMod'  ).value),parseFloat(ById('ucRngModSig' ).value))/100)));

        //Trp10 - blood
        //verified on 11/30 that bloods don't use infantry buff for atk/def. other stats unknown
         ById('ucTrp10Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp10.Life + t.Trp10.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),0)/100)));
         ById('ucTrp10Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp10.Atk  + t.Trp10.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod' ).value),0)/100)));
         ById('ucTrp10Def').innerHTML  = t.round2decimals(                    (t.Trp10.Def  + t.Trp10.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod' ).value),0)/100)));
         ById('ucTrp10Spd').innerHTML  = t.round2decimals(                    (t.Trp10.Spd  + t.Trp10.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod' ).value),0)/100)));
         ById('ucTrp10Rng').innerHTML  = t.round2decimals(                    (t.Trp10.Rng  + t.Trp10.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod' ).value),0)/100)));

        //Trp11 - exec
        //verified on 11/30 that exec don't use infantry buff for atk/def. other stats unknown
         ById('ucTrp11Life').innerHTML = t.round2decimals( (1 + guardLife) *  (t.Trp11.Life + t.Trp11.Life * (resLife                    +  t.maxBuff('life',parseFloat(ById('ucLifeMod').value),0)/100)));
         ById('ucTrp11Atk').innerHTML  = t.round2decimals( (1 + guardAtk)  *  (t.Trp11.Atk  + t.Trp11.Atk  * (resAtk  + knight + itemAtk +  t.maxBuff('atk', parseFloat(ById('ucAtkMod' ).value),0)/100)));
         ById('ucTrp11Def').innerHTML  = t.round2decimals(                    (t.Trp11.Def  + t.Trp11.Def  * (resDef  + knight + itemDef +  t.maxBuff('def', parseFloat(ById('ucDefMod' ).value),0)/100)));
         ById('ucTrp11Spd').innerHTML  = t.round2decimals(                    (t.Trp11.Spd  + t.Trp11.Spd  * (                              t.maxBuff('spd', parseFloat(ById('ucSpdMod' ).value),0)/100)));
         ById('ucTrp11Rng').innerHTML  = t.round2decimals(                    (t.Trp11.Rng  + t.Trp11.Rng  * (                              t.maxBuff('rng', parseFloat(ById('ucRngMod' ).value),0)/100)));

        
    },

    maxBuff : function (stat,a,b) {
        if (stat == 'life')
            if (a+b > 200)
                return 200;
            else
                return a+b;
        if (stat == 'atk')
            if (a+b > 800)
                return 800;
            else
                return a+b;
        if (stat == 'def')
            if (a+b > 4000)
                return 4000;
            else
                return a+b;
        if (stat == 'spd')
            if (a+b > 300)
                return 300;
            else
                return a+b;
        if (stat == 'rng')
            if (a+b > 150)
                return 150;
            else
                return a+b;
    },

    round2decimals : function (number) {
        return Math.round(number * 100) / 100;
    },
    
    woodGuardTable : function (number) {
        if (number == '1')
            return 1;
        else if (number == '2')
            return 2;
        else if (number == '3')
            return 3;
        else if (number == '4')
            return 4;
        else if (number == '5')
            return 6;
        else if (number == '6')
            return 8;
        else if (number == '7')
            return 10;
        else if (number == '8')
            return 13;
        else if (number == '9')
            return 16;
        else if (number == '10')
            return 20;
        else if (number == '11')
            return 25;
        else
            return 0;
    },

    oreGuardTable : function (number) {
        if (number == '1')
            return 2;
        else if (number == '2')
            return 4;
        else if (number == '3')
            return 6;
        else if (number == '4')
            return 8;
        else if (number == '5')
            return 12;
        else if (number == '6')
            return 16;
        else if (number == '7')
            return 20;
        else if (number == '8')
            return 26;
        else if (number == '9')
            return 32;
        else if (number == '10')
            return 40;
        else if (number == '11')
            return 50;
        else
            return 0;
    },
    
     calculate : function () {
        var rb   = parseInt(ById('myrangebuff').value);
        var rdb  = parseInt(ById('myrangedebuff').value);
        var sb   = parseInt(ById('mysiegebuff').value);
        var sdb  = parseInt(ById('mysiegedebuff').value);
        var rrb  = parseInt(ById('myrangedbuff').value);
        var rrdb = parseInt(ById('myrangeddebuff').value);
        var orb   = parseInt(ById('opprangebuff').value);
        var ordb  = parseInt(ById('opprangedebuff').value);
        var osb   = parseInt(ById('oppsiegebuff').value);
        var osdb  = parseInt(ById('oppsiegedebuff').value);
        var orrb  = parseInt(ById('opprangedbuff').value);
        var orrdb = parseInt(ById('opprangeddebuff').value);

        var sdiff = (rb + sb - ordb - osdb) - (orb + osb - rdb - sdb);

        if (sdiff < -25)
            sdiff = -25;
        if (sdiff > 150)
            sdiff = 150;

        var rdiff = (rb + rrb - ordb - orrdb) - (orb + orrb - rdb - rrdb);
        if (rdiff < -25)
            rdiff = -25;
        if (rdiff > 150)
            rdiff = 150;

        ById('siegewinner').value = sdiff;
        ById('rangedwinner').value = rdiff;
    },
    
    loadRCOptions : function () {
        var t = Tabs2.Info;
        readKsRange();
        ById('myrangebuff').value     = KsRange.rb;
        ById('myrangedebuff').value   = KsRange.rdb;
        ById('mysiegebuff').value     = KsRange.sb;
        ById('mysiegedebuff').value   = KsRange.sdb;
        ById('myrangedbuff').value    = KsRange.rrb;
        ById('myrangeddebuff').value  = KsRange.rrdb;
        ById('opprangebuff').value    = KsRange.orb;
        ById('opprangedebuff').value  = KsRange.ordb;
        ById('oppsiegebuff').value    = KsRange.osb;
        ById('oppsiegedebuff').value  = KsRange.osdb;
        ById('opprangedbuff').value   = KsRange.orrb;
        ById('opprangeddebuff').value = KsRange.orrdb;
        t.calculate();
    },
}

/************************************************************************************
*                        KOC POWER - TABS WILD                                        *
************************************************************************************/
var   wildNames={0:culang.kocBog,10:culang.kocGrassland,11:culang.kocLake,20:culang.kocForests,30:culang.kocHill,40:culang.kocMount,50:culang.kocPlain};var   mercNames={0:culang.kocNoneHired,1:culang.kocNovices,2:culang.kocIntermediates,3:culang.kocVeterans}
Tabs.Wilds = {
    tabOrder : TabOptions.toWild,
    tabLabel: culang.tabLabelWild,
    cont : null,
    state : null,
    upGoldTimer : null,
    wildList : [],
    buildList : {},

    show : function (){
        var t = Tabs.Wilds;
        t.init();
    },

    hide : function (){
        var t = Tabs.Wilds;
        clearTimeout (t.upGoldTimer);
    },
    abandon : function (cid,tid,x,y){
        var t = Tabs.Wilds;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        var cityID = cid;
        var tileid = tid;
        params.tid=tid;
        params.cid=cid;
        params.x=x;
        params.y=y;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/abandonWilderness.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess:function(transport){
                var rslt=eval("("+transport.responseText+")");
                if (rslt.ok) {
                    t.error_code = 0;
                    if (rslt.returningMarches) {
                        var cities = Object.keys(rslt.returningMarches);
                        for (var i = 0; i < cities.length; i++) {
                            for (var j = 0; j < rslt.returningMarches[cities[i]].length; j++) {
                                var cid = cities[i].split("c")[1];
                                var mid = rslt.returningMarches[cities[i]][j];
                                var march = Seed.queue_atkp["city" + cid]["m" + mid];
                                if (march) {
                                     var marchtime =  Math.abs(parseInt(march.destinationUnixTime) -  parseInt(march.marchUnixTime));
                                    var ut = unsafeWindow.unixtime();
                                    Seed.queue_atkp["city" + cid]["m" + mid].destinationUnixTime = ut;
                                    Seed.queue_atkp["city" + cid]["m" + mid].marchUnixTime = ut - marchtime;
                                    Seed.queue_atkp["city" + cid]["m" + mid].returnUnixTime = ut + marchtime;
                                    Seed.queue_atkp["city" + cid]["m" + mid].marchStatus = 8
                                }
                            }
                        }
                        t.init();
                    }
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    if (Object.keys(Seed.wilderness["city" + cityID]).length == 1) {
                        Seed.wilderness["city" + cityID] = []
                    } else    {
                        delete Seed.wilderness["city"+cityID]["t"+tileid];
                    }
                } else {
                    t.init();
                    if (rslt.error_code != 401) {
                        t.error_code = rslt.error_code;

                    }
                }
            },
            onFailure: function () {}
        });

    },
    init : function (div){
        var t = Tabs.Wilds;

        uW.ptButMaxTraps = t.e_butMaxTraps;
        uW.ptInpWildTraps = t.e_inpTraps;
        uW.ptButWildSet = t.e_butWildSet;
        uW.ptButWildShow = t.init;
        uW.KsAbandon = t.abandon;
        clearTimeout (t.upGoldTimer);
        if (t.state == null){
            t.cont = div;
            t.cont.innerHTML = '<DIV id=wildContent style="max-height:'+(Options.HauteurBoite-40)+'px; overflow:auto;" >';
            t.state = 1;
        }

        m = '<TABLE cellspacing=0 cellpadding=0 class=ptTabPad align=center width=100%>';
        for (var c=0; c<Cities.numCities; c++){
            var city = Cities.cities[c];
            t.wildList[c] = [];

            var totWilds = 0;
            var datw = Seed.wilderness['city'+ city.id];
            if (datw!=null && matTypeof(datw)=='object')
                for (k in datw)
                    ++totWilds;
            var nivcastle = parseInt(Seed.buildings['city'+ city.id].pos0[1]);
            var castle = nivcastle;
            if (nivcastle==11) castle=12;
            if (nivcastle==12) castle=14;
            if (totWilds < castle)  {
                 var totWildsstring = '<SPAN  style="font-color:red"><B>'+ totWilds +'/'+ castle  +'</b></span>';
            }else{
                var totWildsstring = totWilds +'/'+ castle;
            }


             m += '<TR><TD colspan=21><DIV  class=pdxStat>'+ city.name +' &nbsp; ('+ city.x +','+ city.y +') -  '+totWildsstring+'</div></td></tr>';
            var row = 0;
            var sortem = [];

            var cWilds = Seed.wilderness['city'+city.id];
            if (matTypeof(cWilds) != 'array') {
                 m += '<TR style="font-weight:bold; text-align:center;"  align=right><TD  align=left><u>'+culang.mainWildernes+'</u></td><TD></td><TD   align=left><u>'+culang.shortCoordinate+'</u></td><td><u>'+culang.shortDistance+'</u></td><TD><u>'+culang.wildTraps+'</u></td><TD  align=left><u>'+culang.wildMerc+'</u></td>\
          <TD width=15></td><TD colspan=3 class=entry>'+  htmlTitleLine(' <span  class"shadowCaps">'+culang.wildDefense+'</span> ')  +'</td></tr>';
                for (var k in Seed.wilderness['city'+city.id])
                    sortem.push (Seed.wilderness['city'+city.id][k]);
                sortem.sort (function (a,b){
                    var x; if ((x = b.tileLevel-a.tileLevel)!=0)
                        return x;
                    return a.tileType-b.tileType;
                });
                for (i=0; i<sortem.length; i++){
                    var wild = sortem[i];
                    var wildDef = Seed.wildDef['t'+wild.tileId];
                    if (wildDef==undefined || !wildDef)
                        wildDef = {fort60Count:0, mercLevel:0};
                    var maxTraps = parseInt(wild.tileLevel)*100;
                    var maxBuild = maxTraps - parseInt(wildDef.fort60Count);
                    var distancedelaville = distance (city.x, city.y, wild.xCoord, wild.yCoord);
                    t.wildList[c][i] = [wild.tileId, maxBuild];
                     m += '<TR align=right><TD align=left><a  onclick="KsAbandon('+city.id+','+wild.tileId+','+ wild.xCoord +','+  wild.yCoord +');"><img src="'+IMGdeleteButton+'" border=0  title="'+culang.wildAbandonNote+'"></a>&nbsp;'+  wildNames[wild.tileType] +'</td>\
            <TD>'+ wild.tileLevel +'</td><TD align=center>\
              <a href="javascript:void(0)"  onclick="cm.utils.CoordinateLinkController.onClick(event)"  class="coordinateLink">('+ wild.xCoord +','+ wild.yCoord  +')</a></td><td><b>'+distancedelaville+'</td>\
             <TD align=right><B>'+ wildDef.fort60Count  +'</b></td><TD align=center><B>'+  mercNames[wildDef.mercLevel] +'</b></td>\
             <TD></td><TD align=left  class=pdxEntry><B>'+culang.wildTraps+':</b> <INPUT  onchange="ptInpWildTraps(this)" id=ptwt_'+ c +'_'+ i
                         + (maxBuild==0?' DISABLED ':'')+' style="margin:0px;  padding:0px" type=text size=3 maxlength=4></td>'
                    if (wildDef.fort60Count < maxTraps)
                         m += '<TD class=pdxEntry  style="padding:0px">'+ strButton14(''+culang.shortMax+'', 'id=ptwx_'+  c +'_'+ i +' onclick="ptButMaxTraps(this)"') +'</td>';
                    else
                        m += '<TD class=pdxEntry></td>';
                     m += '<TD class=pdxEntry> &nbsp; &nbsp;  <B>'+culang.wildMerc+':</b> ' + htmlSelector(mercNames,  wildDef.mercLevel, 'id=ptwm_'+ c +'_'+ i) +' &nbsp; &nbsp;  </td></tr>';
                }
                m +=  '<TR><TD colspan=7></td><TD class=pdxEntry  align=center colspan=3><TABLE><TR><TD width=45%  align=left>'+culang.wildCost+': <SPAN id=ptwgc_'+ c  +'>0</span></td>\
            <TD width=10%>'+  strButton20(culang.wildButtonSetWild, 'onclick="ptButWildSet('+ c +')"')  +'<TD width=45% align=right><SPAN id=ptwgt_'+ c  +'></span></td></td></tr></table></td></tr>';
            } else {
                m+= '<TR><TD colspan=10> &nbsp; </td></tr>';
            }
        }
        ById('wildContent').innerHTML = m + '</table></div>';
        t.updateGold ();
    },

    e_butWildSet : function (c){
        var t = Tabs.Wilds;
        var totTraps = 0;
        var cid = Cities.cities[c].id;
        t.buildList = {cityId:cid, list:[]};

        for (var w=0; w<t.wildList[c].length; w++){
            var wild = Seed.wilderness['city'+cid]['t'+t.wildList[c][w][0]];
            var wildDef = Seed.wildDef['t'+t.wildList[c][w][0]];
            if (wildDef==undefined || !wildDef)
                wildDef = {fort60Count:0, mercLevel:0};

            var numTraps = parseInt(ById('ptwt_'+ c +'_'+ w).value, 10);
            if (isNaN(numTraps))
                numTraps = 0;
            totTraps += numTraps;
            if (numTraps > 0)
                t.buildList.list.push (['T', wild.tileId, numTraps]);
            var mercId=ById('ptwm_'+ c +'_'+ w).value;
            if (wildDef.mercLevel != mercId)
                t.buildList.list.push (['M', wild.tileId, mercId, wildDef.mercLevel]);
        }

        var totCost = totTraps * 200;
        if (totCost > parseInt(Seed.citystats['city'+cid].gold[0])){
            ById('ptwgc_'+ c).innerHTML = '<SPAN class=boldRed>'+ addCommasInt(totCost) +'</span>';
            return;
        }
        if (t.buildList.list.length == 0)
            return;
        t.setCurtain (true);
        var popDiv = t.setPopup (true);
        popDiv.innerHTML = '<TABLE class=pdxTab width=100% height=100%><TR><TD>\
          <DIV class=pdxStat>'+culang.wildMercenariesSet+'</div>\
          <DIV id=ptWildBuildDiv class=ptDiv style="padding:10px; max-height:225px; overflow-y:auto"></div>\
           </td></tr><TR><TD align=center>'+  strButton20(''+culang.mainCancel+'', 'id=ptWildCancel')  +'</td></tr></table>';
        ById('ptWildCancel').addEventListener('click', t.e_buildCancel, false);
        t.processQue(null);
    },

    e_buildCancel : function (){
        var t = Tabs.Wilds;
        t.setCurtain(false);
        t.setPopup(false);
        t.init();
    },

    processQue : function (errMsg){
        var t = Tabs.Wilds;
        var what = t.buildList.list.shift();
        var div = ById('ptWildBuildDiv');
        if (what==null || errMsg){
            if (errMsg)
                 div.innerHTML += '<BR><SPAN  style="white-space:normal;" class=boldRed>'+culang.mainError+': '+  errMsg +'</span>';
            else
                div.innerHTML += '<span class="boldGreen">'+culang.mainHDone+'</span><BR>';
            ById('ptWildCancel').firstChild.innerHTML = ''+culang.mainClose+'';
            return;
        }
        if (div.innerHTML != '')
            div.innerHTML += '<span class="boldGreen">'+culang.mainHDone+'</span><BR>';
        var wild = Seed.wilderness['city'+ t.buildList.cityId]['t'+what[1]];
        if (what[0] == 'T'){
             div.innerHTML += ''+culang.wildQueStatusTraps+' '+ what[2] +'  '+culang.wildQueStatusTraps2+' '+ Cities.byID[t.buildList.cityId].name  +''+culang.wildQueStatusTraps3+'  '+ wild.xCoord +','+ wild.yCoord +'  '+culang.wildQueStatusTraps4+' ';
            t.postBuyTraps (t.buildList.cityId, what[1], what[2], t.processQue);
        } else {
             div.innerHTML += ''+culang.wildQueStatusMerc+' '+  mercNames[what[2]] +' '+culang.wildQueStatusMerc2+' '+  Cities.byID[t.buildList.cityId].name +''+culang.wildQueStatusMerc3+' '+  wild.xCoord +','+ wild.yCoord +' '+culang.wildQueStatusMerc4+'';
            t.postHireMercs (t.buildList.cityId, what[1], what[2], what[3], t.processQue);
        }
    },

    setPopup : function (onoff){
        var t = Tabs.Wilds;
        if (onoff){
            var div = document.createElement('div');
            div.id = 'ptWildPop';

             div.setAttribute("style", "opacity: 1; width: 550px;  max-Height: 300px; display: block; position: absolute; top: 100px; left:  100px; z-index:"+mainPop.getLayer()+2+"; oveflow:auto; padding:5px;  border: 1px outset #141516;   -moz-border-radius:"+Options.popupBorderRadius+";  background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee;  -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px  #eee;");



            t.cont.appendChild (div);
            return div;
        } else {
            t.cont.removeChild (ById('ptWildPop'));
        }
    },

    setCurtain : function (onoff){
        var t = Tabs.Wilds;
        if (onoff){
            var off = getAbsoluteOffsets (t.cont);
            var curtain = document.createElement('div');
            curtain.id = 'ptWildCurtain';
            curtain.style.zindex = mainPop.getLayer()+1;
            curtain.style.backgroundColor = "#000000";
            curtain.style.opacity = '0.5';
            curtain.style.width = t.cont.clientWidth +'px';
            curtain.style.height = t.cont.clientHeight +'px';
            curtain.style.display = 'block';
            curtain.style.position = 'absolute';
            curtain.style.top = off.top + 'px';
            curtain.style.left = off.left + 'px';
            t.cont.appendChild (curtain);
        } else {
            t.cont.removeChild (ById('ptWildCurtain'));
        }
    },

    e_butMaxTraps : function (e){
        var t = Tabs.Wilds;
        var c = e.id.substr(5,1);
        var w = e.id.substr(7);
        var inp = ById('ptwt_'+ c +'_'+ w);
        inp.value = t.wildList[c][w][1];
        t.e_inpTraps (inp);
    },

    e_inpTraps : function (e){
        var t = Tabs.Wilds;
        var c = e.id.substr(5,1);
        var w = e.id.substr (7);
        var tot = 0;
        for (var i=0; i<t.wildList[c].length; i++) {
            var val = parseInt(ById('ptwt_'+ c +'_'+ i).value, 10);
            if (isNaN(val))
                val = 0;
            tot += val;
        }
        ById('ptwgc_'+ c).innerHTML = addCommasInt(tot * 200);
        if (isNaN(e.value) || e.value<0 || e.value>t.wildList[c][w][1]){
            e.value = '';
            e.style.backgroundColor = '#ffaaaa';
        } else
            e.style.backgroundColor = null;
    },

    updateGold : function (){
        var t = Tabs.Wilds;
        for (var c=0; c<Cities.numCities; c++){
            var e = ById('ptwgt_'+ c +'');
            if (e)
                e.innerHTML = addCommasInt(Seed.citystats['city'+Cities.cities[c].id].gold[0]);
        }
    },

    postBuyTraps : function (cid, tid, quant, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cid;
        params.tid = tid;
        params.quant = quant;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/buyWildTraps.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){
                    if (!Seed.wildDef["t"+ tid])
                        Seed.wildDef["t"+ tid] = {tileId:tid, fort60Count:0, mercLevel:0};
                    Seed.wildDef["t"+ tid].fort60Count = parseInt(Seed.wildDef["t"+ tid].fort60Count) + parseInt(quant);
                }
                if (notify)
                    notify (rslt.errorMsg);
            },
            onFailure: function () {
                if (notify)
                    notify ('AJAX ERROR');
            },
        });
    },

    postHireMercs : function (cid, tid, newLevel, oldLevel, notify){

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cid;
        params.tid = tid;
        params.lv = newLevel;
        params.olv = oldLevel;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/hireWildMerc.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){
                    if (!Seed.wildDef["t"+ tid])
                        Seed.wildDef["t"+ tid] = {tileId:tid, fort60Count:0, mercLevel:0};
                    Seed.wildDef["t"+ tid].mercLevel = newLevel;
                }
                if (notify)
                    notify (rslt.errorMsg);
            },
            onFailure: function () {
                if (notify)
                    notify ('AJAX ERROR');
            },
        });
    },
}
/************************************************************************************
 *                        KOC POWER - TABS KNIGHTS                                    *
 ************************************************************************************/
Tabs.Knights = {
    tabOrder: TabOptions.toKnights,
    tabLabel: culang.tabLabelKnights,
    cont : null,
    state : null,
    displayTimer : null,
    action : 0,
    show : function (){
        var t = Tabs.Knights;
        t.showDiv();
    },
    hide : function (){
        var t = Tabs.Knights;
        clearTimeout (t.displayTimer);
    },
    init : function (div){
        var t = Tabs.Knights;
        unsafeWindow.ptAssignSkill = t.clickedAssignPoints;
        unsafeWindow.ptAssignTunes = t.clickedAssignTune;
        t.cont=div;
        clearTimeout (t.displayTimer);
        if (t.state == null){
             t.cont.innerHTML = '<STYLE>table.ptTabPad tr.ptwpad  {background-color:#ffffff; padding-left:5px}</style>\
            <DIV id=ptknightdiv style="max-height:'+(Options.HauteurBoite-40)+'px; overflow:auto;">';
            t.state = 1;
        }
        t.showDiv();
    },
    showDiv: function() {
        var t = Tabs.Knights;
        function _dispKnight (roleId, knight, numcid){
            var rid = roleId;
            if (roleId==null)
                rid = 1;
            var sty='';
            if (row++ % 2)
                sty = ' ';
             m = '<TR '+ sty +'valign=top  align=right><TD><font size=1><B>'+ (roleId==null ?  '':knightRoles[rid][0]) +'</b></td><TD align=left>';
            if (knight == null) {
                 m += '--------</td><TD  colspan=5></td><TD class=pdxEntry  colspan=5></td><TD colspan=2></td></tr>';
            } else {
                var level = parseInt(Math.sqrt(parseInt(knight.experience) / 75)) + 1;
                var unpoints = level - parseInt(knight.skillPointsApplied);
                var salary = (parseInt(knight.skillPointsApplied) + 1) * 20;
                totSalary += salary;
                var ass = '';
                if (knight.knightStatus == 10){
                    ass = '<TD class=pdxEntry align=left colspan=4><i>'+culang.mainMarch+'</i></td>';
                } else {
                    if (unpoints > 0){
                        unpoints = '<SPAN class="boldRed">'+ unpoints +'</span>';
                        for (var i=0; i<4; i++){
                            var sty = 'padding-left:1px;';
                            if (i == rid) {
                                sty += 'font-weight:bold;color:#116654';
                                if (t.action==1) {
                                    t.clickedAssignPoints(null, cid,knight.knightId,i);
                                }
                                if (t.action==2) {
                                    t.clickedAssignPoints(null, cid,knight.knightId,1);
                                }
                            }
                             ass += '<TD class=pdxEntry align=left  style="'+ sty +'" ><A style="'+ sty +'"  onclick="ptAssignSkill(this,' + cid +','+ knight.knightId +','+ i  +')">['+ knightRoles[i][2] +'] &nbsp;</a></td>';
                        }
                    }
                    else
                        ass = '<TD class=pdxEntry colspan=4></td>';
                }
                var now = unixTime();
                var skills = [];
                for (var i=0; i<4; i++){
                    if (i == rid) {
                        var point = knight[knightRoles[i][1]];
                        skills[i] = '<B>'+ point +'</b>';
                        if (i==1 && knight.combatBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsCombatBoost+'  '+timestr(knight.combatBoostExpireUnixtime - now)+'"><B>'+  parseInt(point) +'</b></span></font>';
                        }
                        if (i==0 && knight.politicsBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsPoliticBoost+'  '+timestr(knight.politicsBoostExpireUnixtime - now)+'"><B>'+  parseInt(point) +'</b></span></font>';
                        }
                        if (i==3 && knight.resourcefulnessBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsResBoost+'  '+timestr(knight.resourcefulnessBoostExpireUnixtime -  now)+'"><B>'+ parseInt(point)  +'</b></span></font>';
                        }
                        if (i==2 && knight.intelligenceBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsIntBoost+'  '+timestr(knight.intelligenceBoostExpireUnixtime -  now)+'"><B>'+ parseInt(point)  +'</b></span></font>';
                        }
                    } else {
                        var point = knight[knightRoles[i][1]];
                        skills[i] = ''+ point +'';
                        if (i==1 && knight.combatBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsCombatBoost+'  '+timestr(knight.combatBoostExpireUnixtime - now)+'">'+  parseInt(point) +'</span></font>';
                        }
                        if (i==0 && knight.politicsBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsPoliticBoost+'  '+timestr(knight.politicsBoostExpireUnixtime - now)+'">'+  parseInt(point) +'</span></font>';
                        }
                        if (i==3 && knight.resourcefulnessBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsResBoost+'   '+timestr(knight.resourcefulnessBoostExpireUnixtime - now)+'">'+  parseInt(point) +'</span></font>';
                        }
                        if (i==2 && knight.intelligenceBoostExpireUnixtime > now) {
                            point *= 1.25;
                             skills[i] = '<font color=red><span  title="'+culang.knightsIntBoost+'  '+timestr(knight.intelligenceBoostExpireUnixtime - now)+'">'+  parseInt(point) +'</span></font>';
                        }
                    }
                }
                var item211="0";
                var item221="0";
                var item231="0";
                var item241="0";
                 if (Seed.items.i211) item211='<a  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ boost_modal(1,'+  knight.knightId +');return false;},  500);">'+Seed.items.i211+'</a>';
                if  (Seed.items.i221) item221='<a  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ boost_modal(2,'+  knight.knightId +');return false;},  500);">'+Seed.items.i221+'</a>';
                if  (Seed.items.i231) item231='<a  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ boost_modal(3,'+  knight.knightId +');return false;},  500);">'+Seed.items.i231+'</a>';
                if  (Seed.items.i241) item241='<a  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ boost_modal(4,'+  knight.knightId +');return false;},  500);">'+Seed.items.i241+'</a>';
                m += '<a  title="'+culang.knightsAssignRoleNote+'"  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ assign_role_modal('+  knight.knightId +');return false;}, 500);">' +  knight.knightName.substring(0,20) +  '</a></td><TD><a  title="'+culang.knightsAssignLvlUp+'"  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){  xpBoost_modal('+  knight.knightId +');return false; }, 500);"  href="javascript:void(0)">'+ level +'</a></td>\
               <TD>'+ skills[0] +' ('+item211+')</td><TD>'+  skills[1] +' ('+item221+')</td><TD>'+ skills[2] +'  ('+item231+')</td><TD>' + skills[3]
                     +' ('+item241+')</td><TD class=pdxEntry>'+ unpoints  +'</td>'+ ass +'<td><a  onclick="citysel_click(document.getElementById(\'citysel_'+  (numcid+1)+'\'));setTimeout (function (){ loyalBoost_modal('+  knight.knightId +');return false;}, 500);"  colspan=2>'+knight.loyalty+'</a><img  onclick="ptAssignTunes(' + cid +','+ knight.knightId +');"  src="'+IMGgold16+'"  title="'+culang.knightsAssignLoy+'"></td><TD>'+  addCommas(salary) +'</td></tr>';
            }
            return m;
        }

        var totSalary = 0;
         var m = '<DIV  class=pdxStat>'+culang.knightsHead+'</div><center><b>'+culang.knightsAssignPoints+'</b>  <input style="height:20px;font-size:9px;" type=button  value="'+culang.mainDefault+'" id="ksAssignDefault"><input  style="height:20px;font-size:9px;" type=button  value="'+culang.kocCombat+'" id="ksAssignCombat">  <b>'+culang.knightsAssignPoints2+'</b></center><TABLE  cellspacing=0 align=center class=ptTabPad>';
        for (var c=0; c<Cities.numCities; c++) {
            var city = Cities.cities[c];
            var cid = Cities.cities[c].id;
             m += '<tr><TD colspan=15><DIV  class=pdxStat>'+ Cities.cities[c].name +' &nbsp; ('+ city.x +','+  city.y +') </div></td></tr>\
          <TBODY  id="Kskin'+cid+'"><TR style="font-weight:bold"  align=right><TD  width=70>'+culang.knightsRole+'</td><TD width=140  align=center>'+culang.mainName+'</td><TD  width=22>'+culang.shortLevel+'</td><TD  width=25>'+culang.kocShortPolitics+'</td><TD  width=25>'+culang.kocShortCombat+'</td>\
          <TD  width=25>'+culang.kocShortIntelligence+'</td><TD  width=25>'+culang.kocShortRessource+'</td><TD width=75  align=center colspan=5>-- '+culang.knightsAssignskills+'  --</td><td witdh=25  colspan=1>'+culang.knightsLoy+'</td><TD width=40  align=right>'+culang.knightsCost+'</td></tr>';
            totSalary = 0;
            var did = {};
            var row = 0;
            for (var i=0; i<knightRoles.length; i++){
                var leader = Seed.leaders['city'+cid][knightRoles[i][1]+'KnightId'];
                if (leader == 0)
                    m += _dispKnight (i, null, c);
                else {
                    m += _dispKnight (i, Seed.knights['city'+cid]['knt'+leader], c);
                    did['knt'+leader] = true;
                }
            }
            var list = [];
            for (k in Seed.knights['city'+cid]){
                if (!did[k])
                    list.push (Seed.knights['city'+cid][k]);
            }
            list.sort (function (a,b){return parseInt(b.combat)-parseInt(a.combat)});
            for (i=0; i<list.length; i++)
                m += _dispKnight (null, list[i], c);
             m += '<TR align=right><TD  colspan=13><B>'+culang.knightsTotalCost+':</b></td><TD>'+  addCommas(totSalary) +'</td></tr></TBODY>';
        }
        ById('ptknightdiv').innerHTML = m +'</table></div>';


        t.action = 0;
        but = ById('ksAssignDefault');
        but.addEventListener ('click', function (){
            t.action=1;
            t.showDiv();
        }, false);
        but = ById('ksAssignCombat');
        but.addEventListener ('click', function (){
            t.action=2;
            t.showDiv();
        }, false);
        t.displayTimer = setTimeout (t.showDiv, 5000);
    },

    clickedAssignTune: function(cid, kid) {
        var t = Tabs.Knights;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cid;
        params.kid = kid;
        params.rid=0;
        params.standalone=0;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/rewardKnight.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    var knight = Seed.knights["city" + cid]["knt" + kid];
                    knight.loyalty = parseInt(knight.loyalty) + 5;
                }
            },
            onFailure: function () {
            },
        });
    },
    clickedAssignPoints : function (e, cid, kid, rid){
        var t = Tabs.Knights;
        clearTimeout (t.displayTimer);
try {
        var knight = Seed.knights['city'+cid]['knt'+kid];
        if (knight.knightStatus == 10 && e!=null){
            var row = e.parentNode.parentNode;
            row.childNodes[9].innerHTML = uW.g_js_strings.commonstr.marching;
            return;
        }
        sk = [];
        var unassigned = parseInt(Math.sqrt(parseInt(knight.experience)/75)) + 1  - parseInt(knight.skillPointsApplied);


        for (var i=0; i<4; i++){
            sk[i] = parseInt(knight[knightRoles[i][1]]);
            if (i == rid) {
                if ((sk[i]+unassigned)>=255) {
                    unassigned=255-sk[i];
                    sk[i]=255;

                }else{
                    sk[i] += unassigned;
                }
            }
        }
        if (unassigned==0) return;
        if (e!=null) {
            var row = e.parentNode.parentNode;
            for (i=row.cells.length-1; i>=1; i--)
                row.deleteCell (i);
            var newCell=row.insertCell(-1);
            newCell.colSpan = 12;
            newCell.align= 'left';
            newCell.style.padding='1px 5px 1px 10px';
            var div = document.createElement ('div');
            div.style.backgroundColor = '#ffffff';
            div.style.textAlign = 'center';
            div.style.border = '1px solid';
            div.style.width = '98%';
            div.style.whiteSpace = 'normal';
            newCell.appendChild (div);
             div.innerHTML = ''+culang.knightsSetPoints+' <span  class="boldRed">'+ unassigned +'</span>  '+culang.knightsSetPoints2+' '+ knightRoles[rid][1] +'  '+culang.knightsSetPoints3+' ';
        }
        t.postSkillPoints (cid, kid, sk[0], sk[1], sk[2], sk[3], function (r){t.postDone(r, div)});
    } catch (ex) {
        alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
    }
    },

    postDone : function (rslt, div){
        var t = Tabs.Knights;
        clearTimeout (t.displayTimer);
        if (rslt.ok){
            if (div) div.innerHTML += '<span class="boldGreen">'+culang.mainOK+'</span>';
            t.displayTimer = setTimeout (t.showDiv, 5000);
        } else {
             if (div) div.innerHTML += '<BR><SPAN  class=boldRed>'+culang.mainError+': '+ rslt.errorMsg  +'</span>';
            t.displayTimer = setTimeout (t.showDiv, 5000);
        }
    },

    postSkillPoints : function (cid, kid, pol, com, int, res, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cid;
        params.kid = kid;
        params.p = pol;
        params.c = com;
        params.i = int;
        params.r = res;

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/skillupKnight.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    var knight = Seed.knights["city" + cid]["knt" + kid];
                     var up = pol + com + int + res - knight.politics -  knight.combat - knight.intelligence - knight.resourcefulness;
                    knight.politics = pol;
                    knight.combat = com;
                    knight.intelligence = int;
                    knight.resourcefulness = res;
                    knight.skillPointsApplied = (parseInt(knight.skillPointsApplied) + up).toString();
                }
                if (notify)
                    notify (rslt);
            },
            onFailure: function () {
                if (notify)
                    notify (rslt);
            },
        });
    },
};
/************************************************************************************
*                        KOC POWER - TABS AUTO SCOUT                                    *
************************************************************************************/
Tabs.ScoutAlliance = {
    tabOrder : TabOptions.toScoutAlliance,
    tabLabel: culang.tabLabelAutoScout,
    myDiv : null,
    MapAjax : new CMapAjax(),
    ScoutAllianceOptions : {
        num_scouts     : 1,
        min_might      : 500000,
        max_might      : 100000000,
        scout_interval : 5,
        scouting       : false,
        scout_ready    : false,
        scoutage : {},
    },

    init : function (div){
        var t = Tabs.ScoutAlliance;
        var o = t.ScoutAllianceOptions;
        unsafeWindow.fetchAllianceMembers = t.eventGetMembers;
        t.myDiv = div;
        t.city = 0;
        t.citiesToScout = {};

        var s = GM_getValue('ScoutAllianceOptions_' + getServerId());
        if (s != null){
            t.ScoutAllianceOptions = JSON2.parse(s);
        }

        for(var i=0; i < Cities.numCities; i++) {
            t.citiesToScout[i] = [];
            var s = GM_getValue('CitiesToScout_city_' + i + '_' + getServerId());
            if (s != null){
                t.citiesToScout[i] = JSON2.parse(s);
            }
        }

        t.show();
        t.doNextScout();
    },


    setScoutAllianceOptions : function () {
        var t = Tabs.ScoutAlliance;
        GM_setValue ('ScoutAllianceOptions_' + getServerId(), JSON2.stringify(t.ScoutAllianceOptions));
    },

    show : function (){
        var t = Tabs.ScoutAlliance;
        var o = t.ScoutAllianceOptions;

        if (t.state == null){
            if (getMyAlliance()[0] == 0) {
                 t.myDiv.innerHTML =  '<BR><CENTER><b><i>'+culang.autoScoutNeedAlliance+'</i></b></center>';
                t.state = 1;
                return;
            }
             var m = '<DIV  class=pdxStat>'+culang.autoScoutHead+'</div><DIV  class=pbentry><TABLE width=100% cellpadding=0 class=pdxTab>';
            if (o.scouting) {
                 m += '<TD><INPUT id=IdScoutingStatus type=submit  value="'+culang.tabLabelAutoScout+' =  '+culang.buttonON+'"></td>';
            } else {
                if (o.scout_ready) {
                     m += '<TD><INPUT id=IdScoutingStatus  type=submit value="'+culang.tabLabelAutoScout+' =  '+culang.buttonOFF+'"></td>';
                } else {
                     m += '<TD><INPUT id=IdScoutingStatus  type=submit value="'+culang.tabLabelAutoScout+' =  '+culang.autoScoutNotReady+'"></td>';
                }
            }
             m += '<TR><TD>'+culang.mainIntervall+': <INPUT  id=IdScoutInterval type=text size=2 maxlength=3 value='+  o.scout_interval +' \> '+culang.mainSeconds+'</td>';
             m += '<TD>'+culang.autoScoutAmount+': <INPUT  id=IdNumScouts type=text size=8 maxlength=8 value='+ o.num_scouts +'  \></td></tr>';
            m +=  '<TR><TD>'+culang.autoScoutMinMight+' <INPUT  id=IdMinMight type=text size=9 maxlength=11 value='+ o.min_might +'  \></td>';
            m +=  '<TD>'+culang.autoScoutMaxMight+' <INPUT id=IdMaxMight  type=text size=9 maxlength=11 value='+ o.max_might +'  \></td></tr>';

            m += '<TR><TD class=xtab>'+culang.autoScoutAlliance+' &nbsp;</td>';
            m += '<TD class=xtab><INPUT id=IdSearchAllianceName type=text /> &nbsp;';
             m += '<INPUT id=IdSearchAllianceNameSubmit type=submit  value="'+culang.autoScoutSearchAlliance+'" /></td></tr>';
             m += '<TR><TD class="xtab ptErrText"><SPAN  id=IdScoutAllianceErrorSpan></span></td></tr>';
            m += '</table><div style="vertical-align:middle;" id=IdScoutAlliance></div></div>';
            m += '<div style="max-height:350px; overflow-y:auto;" id=IdScoutAllianceStatus></div>';
            m += '<div style="max-height:400px; overflow-y:auto;" id=IdScoutAllianceProgress></div></div>';
            t.myDiv.innerHTML = m;

            ById('IdScoutInterval').addEventListener('change', function(){
                o.scout_interval=parseInt(ById('IdScoutInterval').value);
                t.setScoutAllianceOptions();
            },false);
            ById('IdNumScouts').addEventListener('change', function(){
                o.num_scouts=parseInt(ById('IdNumScouts').value);
                t.setScoutAllianceOptions();
            },false);
            ById('IdMinMight').addEventListener('change', function(){
                o.min_might=parseInt(ById('IdMinMight').value);
                t.setScoutAllianceOptions();
            },false);
            ById('IdMaxMight').addEventListener('change', function(){
                o.max_might=parseInt(ById('IdMaxMight').value);
                t.setScoutAllianceOptions();
            },false);
            ById('IdSearchAllianceNameSubmit').addEventListener ('click', t.SearchAllianceSubmit, false);
            ById('IdScoutingStatus').addEventListener('click', function(){t.toggleScoutingStatus(this)} , false);
            t.state = 1;
        }
    },

    hide: function(){
    },

    SearchAllianceName : '',
    SearchAllianceSubmit : function (){
        var t = Tabs.ScoutAlliance;
        ById('IdScoutAllianceErrorSpan').innerHTML='';
        t.SearchAllianceName = ById('IdSearchAllianceName').value;
        if (t.SearchAllianceName.length < 3){
             ById('IdScoutAllianceErrorSpan').innerHTML = '<div  class=pdxStat>'+culang.mainError+'</div><i>'+culang.autoScoutAllianceMinValue+'</i>';
            return;
        }
         ById('IdScoutAllianceStatus').innerHTML = '<DIV  class=pdxStat>'+culang.autoScoutSearchHead+' "'+ t.SearchAllianceName  +'"...';
        t.fetchAllianceList (t.SearchAllianceName, t.eventGotAllianceList);
    },

    eventGotAllianceList : function (rslt){
        var t = Tabs.ScoutAlliance;
        if (!rslt.ok){
            ById('IdScoutAllianceStatus').innerHTML = rslt.errorMsg;
            ById('IdScoutAllianceErrorSpan').innerHTML = rslt.errorMsg;
            return;
        }
         var m = '<DIV class=pdxStat>'+culang.autoScoutResultHead+'  <B>"'+ t.SearchAllianceName +'"</b></div>\
     <TABLE class=pdxTab><TR style="font-weight:bold"><TD  class=xtab><b><u>'+culang.mainName+'</u></b></td><TD   class=xtab><b><u>'+culang.mainRank+'</u></b></td><TD   class=xtab><b><u>'+culang.mainPlayer+'</u></b></td>\
         <TD align=right  class=xtab><b><u>'+uW.g_js_strings.commonstr.might+'</u></b></td><TD   class=xtab><b><u>'+culang.mainDiplo+'</u></b></td><TD  class=xtab></td></tr>';
        for (k in rslt.alliancesMatched){
            var all = rslt.alliancesMatched[k];
            var dip = '';
            if (all.relation && all.relation==1)
                dip = ''+culang.kocFriendly+'';
            else if (all.relation && all.relation==2)
                dip = ''+culang.kocHostile+'';
             m += '<TR><TD class=xtab>'+ all.allianceName  +'</td><TD align=right class=xtab>'+ all.ranking  +'</td><TD align=right class=xtab>'+ all.membersCount  +'</td>\
       <TD align=right class=xtab>'+ addCommasInt(all.might) +'</td><TD class=xtab>'+ dip +'</td>\
        <TD class=xtab><a onclick="fetchAllianceMembers('+  all.allianceId  +')">'+culang.autoScoutMember+'</a></td></tr>';
        }
        ById('IdScoutAllianceStatus').innerHTML = m;
    },

    fetchAllianceList : function (allianceName, notify) {
        var t = Tabs.ScoutAlliance;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.allianceName = allianceName;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetSearchResults.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errorMsg:'AJAX error'});
            },
        });
    },

    eventGetMembers : function (aid){
        var t = Tabs.ScoutAlliance;
        t.ScoutAllianceOptions.scout_ready = false;
        t.setScoutAllianceOptions();
        ById('IdScoutingStatus').value = ""+culang.tabLabelAutoScout+" = "+culang.autoScoutNotReady+"";
        ById('IdScoutAllianceStatus').innerHTML = '<DIV class=pdxStat>'+culang.autoScoutLoadPlayer+'</div>';
        ById('IdScoutAllianceProgress').innerHTML = '';
        t.fetchAllianceMemberList (aid, t.eventGotMemberList);
    },

    fetchAllianceMemberList : function (allianceId, notify) {
        var t = Tabs.ScoutAlliance;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.perPage = 100;
    params.type = 'might';
    params.page = 1;
        params.allianceId = allianceId;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errorMsg:'AJAX error'});
            },
        });
    },

    eventGotMemberList : function (rslt){
        var t = Tabs.ScoutAlliance;
        var o = t.ScoutAllianceOptions;
        ById('IdScoutAllianceProgress').innerHTML="";
        if (!rslt.ok){
            ById('IdScoutAllianceStatus').innerHTML = rslt.errorMsg;
            ById('IdScoutAllianceErrorSpan').innerHTML = rslt.errorMsg;
            return;
        }
        var numInvalid = 0;
        var numPlayers = 0;
        var numCities = 0;
        var myA = getMyAlliance ();
        var dist = 0;
        for(var i=0; i < Cities.numCities; i++) {
            t.citiesToScout[i] = [];
        }
        for (var r=0; r<rslt.results.length; r++){
            p = rslt.results[r];
            if (p.userId == 0){
                ++numInvalid;
            } else {
                ++numPlayers;
                numCities += p.cities.length;
                might = parseInt(p.might);
                if (might > parseInt(o.min_might) && might < parseInt(o.max_might)) {
                    for (var c=0; c<p.cities.length; c++){
                        for(var i=0; i < Cities.numCities; i++) {
                            dist = distance (Cities.cities[i].x, Cities.cities[i].y, p.cities[c].xCoord, p.cities[c].yCoord);
                            t.citiesToScout[i].push ({x:p.cities[c].xCoord,y:p.cities[c].yCoord, dist:dist, nom:p.displayName});
                        }
                    }
                }
            }
        }

        dist = 100000;
        for(var i=0; i < Cities.numCities; i++) {
             t.citiesToScout[i].sort(function sortDist(a,b) {a =  a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
            if (t.citiesToScout[0].length > 0 && t.citiesToScout[i][0].dist < dist) {
                t.city = i;
                dist = t.citiesToScout[i][0].dist;
            }
            GM_setValue('CitiesToScout_city_' + i + '_' + getServerId(), JSON2.stringify(t.citiesToScout[i]));
        }
        if (t.city == 0) t.city = Cities.numCities;
        else t.city -= 1;

        var m = '';
        m += '<DIV class=pdxStat>'+ rslt.allianceName +' ('+culang.mainPlayer+': ' + numPlayers + ' ';
        if (numInvalid > 0) m += ' ('+culang.mainInFog+': ' + numInvalid + ')';
        m += ' - '+culang.mainCities+': ' +t.citiesToScout[0].length+ ' ';
        if (t.citiesToScout[0].length != numCities) m += ' ('+culang.mainTotal+': ' + numCities + ')';
        m += ')</div><div>';
        ById('IdScoutAllianceStatus').innerHTML = m;
        if (t.citiesToScout[0].length > 0) {
            t.ScoutAllianceOptions.scout_ready = true;
            t.setScoutAllianceOptions();
            ById('IdScoutingStatus').value = culang.tabLabelAutoScout+" = "+culang.buttonOFF;
        }
    },
    toggleScoutingStatus: function(obj){
        var t = Tabs.ScoutAlliance;
        var o = t.ScoutAllianceOptions;
        if (!o.scout_ready) return;
        if (o.scouting) {
            o.scouting = false;
            t.setScoutAllianceOptions();
            obj.value = culang.tabLabelAutoScout+" = "+culang.buttonOFF;
            t.nextscout = null;
        } else {
            o.scouting = true;
            t.setScoutAllianceOptions();
            obj.value = culang.tabLabelAutoScout+" = "+culang.buttonON;
            t.doNextScout();
        }
    },
    doNextScout: function(){
        var t = Tabs.ScoutAlliance;
        var o = t.ScoutAllianceOptions;
        if (!o.scout_ready) return;
        if (!o.scouting) return;
        var slots = 0;
        var can_scout = false;
        that_city = t.city;
        var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);
        do {
            t.city += 1;
            if (t.city>=Seed.cities.length){
                t.city=0;
            }

            this_city = t.city;
            if (this_city == that_city) {
                t.nextscout = setTimeout(t.doNextScout,(parseInt(o.scout_interval)*1000));
                return;
            }

            city = Cities.cities[this_city];

            if (t.citiesToScout[this_city].length == 0) {
                o.scout_ready = false;
                o.scouting = false;
                t.setScoutAllianceOptions();
                ById('IdScoutingStatus').value = ""+culang.tabLabelAutoScout+" = "+culang.autoScoutNotReady+"";
                t.nextscout = null;
                return;
            }

            if(parseInt(Seed.units['city'+city.id]['unt'+3]) < parseInt(o.num_scouts)){
                continue;
            }
            var RInfo = getRallypointInfo(city.id);
            var rallypointlevel = RInfo.maxMarches;
            var slots = RInfo.usedSlots;
            
            id=t.citiesToScout[this_city][0].x+","+t.citiesToScout[this_city][0].y;
            if (t.ScoutAllianceOptions.scoutage[id]) {
                last = t.ScoutAllianceOptions.scoutage[id];
                if ( now < (parseInt(last) + (24 * 60 * 60))){
                    t.scout_delete(t.citiesToScout[this_city][0].x,t.citiesToScout[this_city][0].y);
                    continue;
                }
            }
            if(slots >= rallypointlevel){
                continue;
            }
            can_scout = true;

        } while (!can_scout);

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = city.id;
        params.kid = 0;
        params.type = 3;
        params.xcoord = t.citiesToScout[this_city][0].x;
        params.ycoord = t.citiesToScout[this_city][0].y;
        params.u3 = parseInt(o.num_scouts);
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unixTime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var currentcityid = params.cid;
                     unsafeWindow.attach_addoutgoingmarch(rslt.marchId,  rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord,  unitsarr, params.type, params.kid, resources, rslt.tileId,  rslt.tileType, rslt.tileLevel, currentcityid, true);
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                     ById('IdScoutAllianceProgress').innerHTML += '<div  class=pdxStat>'+culang.autoScoutAttackHead+'</div><center><i>'+culang.autoScoutSend+'  '+city.name+' '+culang.autoScoutSend2+'  '+t.citiesToScout[this_city][0].nom+' '+params.xcoord+',  '+params.ycoord+' '+culang.autoScoutSend3+'  '+t.citiesToScout[this_city][0].dist+'</i></center>';
                    t.scout_done(params.xcoord, params.ycoord);
                    t.nextscout = setTimeout(t.doNextScout,(o.scout_interval*1000));
                } else {
                     rslt.errorMsg =  unsafeWindow.printLocalError((rslt.error_code || null), (rslt.msg ||  null), (rslt.feedback || null));
                     ById('IdScoutAllianceProgress').innerHTML += '<div  class=pdxStat>'+culang.mainError+'</div><center><i>'+culang.autoScoutSendError+'  '+city.name+' '+culang.autoScoutSendError2+'  '+t.citiesToScout[this_city][0].nom+' '+params.xcoord+',  '+params.ycoord+' ['+rslt.errorMsg+']</i></center>';
                    if (rslt.error_code==208) t.scout_done(params.xcoord, params.ycoord);
                    t.nextscout = setTimeout(t.doNextScout,(o.scout_interval*1000));
                }
            },
            onFailure: function () {}
        });
    },

    getRallypoint: function(cityId){
        var t = Tabs.ScoutAlliance;
        cityId = 'city'+cityId;
        for (o in Seed.buildings[cityId]){
            var buildingType = parseInt(Seed.buildings[cityId][o][0]);
            var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
            if (buildingType == 12){
                return parseInt(buildingLevel);
                break;
            }
        }
        return 0;
    },
    scout_delete : function(x,y) {
        var t = Tabs.ScoutAlliance;
        var id = x + "," + y;

        for(var i=0; i < Cities.numCities; i++) {
            for (var c=0; c < (t.citiesToScout[i].length); c++) {
                 if (parseInt(t.citiesToScout[i][c].x) == parseInt(x)  && parseInt(t.citiesToScout[i][c].y) == parseInt(y)) {
                    t.citiesToScout[i].splice(parseInt(c), 1);
                }
            }
        }
         ById('IdScoutAllianceProgress').innerHTML += '<div  class=pdxStat>'+culang.mainError+'</div><center><i>'+culang.autoScoutSendRestriction+'  '+t.citiesToScout[this_city][0].nom+'  '+culang.autoScoutSendRestriction2+' '+x+', '+y+' <span  class="boldRed">'+culang.autoScoutSendRestriction3+'</span></i></center>';

    },
    scout_done: function(x,y){
        var t = Tabs.ScoutAlliance;
        var cnt = 0;
        for(var i=0; i < Cities.numCities; i++) {
            for (var c=0; c < (t.citiesToScout[i].length); c++) {
                 if (parseInt(t.citiesToScout[i][c].x) == parseInt(x)  && parseInt(t.citiesToScout[i][c].y) == parseInt(y)) {
                    var now = new Date().getTime()/1000.0;
                    now = now.toFixed(0);
                    var id = x + "," + y;
                    t.ScoutAllianceOptions.scoutage[id] = now;
                    t.setScoutAllianceOptions();
                    t.citiesToScout[i].splice(parseInt(c), 1);
                    GM_setValue('CitiesToScout_city_' + i + '_' + getServerId(), JSON2.stringify(t.citiesToScout[i]));
                    cnt++;
                    break;
                }
            }
        }
        if (cnt != Cities.numCities) {
        }
    },
}
/************************************************************************************
*                        KOC POWER - TABS APOTHECARY                                    *
************************************************************************************/
Tabs.Apothecary = {
    tabLabel : culang.tabLabelApothecary,
    tabOrder : TabOptions.toApothecary,
    cities : [],
    pop : null,
    pop2 : null,
    myDiv : null,
    timer : null,

    init : function (div){    // called once, upon script startup
        var t = Tabs.Apothecary;
        t.myDiv = div;
        unsafeWindow.pbapo = t.display_action;
         var m = '<DIV class=pdxStat  >'+culang.apothecaryHead+'</div><table width=100% height=0%  class=pdxTab><tr align=center >';
        m +=  '<td><input type=submit id=pbapothecary_power  value="'+culang.apothecaryAutoHeal+' =  '+(ApothecaryOptions.Active?''+culang.buttonON+'':''+culang.buttonOFF+'')+'"  /></td>\
          <td><input type=submit  id=pbapothecary_show value="'+culang.mainShow+'"  /></td></tr></table>';
        m += '<DIV  class=pdxStat id=pbapothecary_options  >'+culang.apothecaryHeadSettings+'</div></div><table></tr>\
           <td>'+culang.apothecaryKeepGold+' <INPUT type=text  id="pbapothecary_gold" size=6 value='+ApothecaryOptions.goldkeep+'  /></td>\
          <td colspan=4><span id="pbapothecary_citysel"></span></td></tr><tr>\
           <td>'+culang.apothecaryTroopType+' <SELECT  id="pbapothecary_troops"><option value=0>--  '+culang.mainSelect+' --</options>';
        for (y in unsafeWindow.unitcost)
            m += '<option value="'+y.substr(3)+'">'+unsafeWindow.unitcost[y][0]+'</option>';
        m += '</select></td>\
          <td>'+culang.shortMin+': <INPUT id=pbapothecary_min type=text size=4 \></td>\
           <td><INPUT type=checkbox id=pbapothecary_maxcheck />  '+culang.shortMax+': <INPUT id=pbapothecary_max type=text size=4  DISABLED \></td>\
          <td><INPUT type=submit id=pbapothecary_save value="'+culang.buttonAdd+'" /></td>';
        m += '</tr></table>';
         m +="<DIV  class=pdxStat>"+culang.apothecaryHeadTroops+"</div><br><span  id=KsApothecaryTroops></span>"
        div.innerHTML = m;
        for (var cid in Cities.byID){
            var city = 'city'+cid;
            var x = Cities.byID[cid].idx;
            t.cities[x] = true;
            for (var y in Seed.buildings[city]) {
                if (Seed.buildings[city][y][0] == 21 || Seed.buildings[city][y][0] == 23){
                    t.cities[x] = false;
                    continue;
                }
            }
        }
        t.citysel = new CdispCityPicker('Ksapo_sel', $("pbapothecary_citysel"), true, null, 0, t.cities);

        $("pbapothecary_gold").addEventListener('change', function(){
            ApothecaryOptions.goldkeep = parseIntNan(this.value);
        },false);
        $("pbapothecary_maxcheck").addEventListener('click', function(){
            $("pbapothecary_max").disabled = !($("pbapothecary_maxcheck").checked);
        },false);
        $("pbapothecary_save").addEventListener('click', function(){
            t.e_addqueue();
        },false);
        $("pbapothecary_power").addEventListener('click', function(){
            t.e_toggleswitch(this);
        },false);
        $("pbapothecary_show").addEventListener('click', function(){
            t.e_displayarray();
        },false);
        t.timer = setTimeout(t.loop,15000);
        t.displayStat();

    },
    displayStat: function() {
        var t = Tabs.Apothecary;
        var m="<table width=98% align=center  class=pdxTab><tr><td>&nbsp;</td>";
        for(var i=0; i<Cities.numCities; i++) {
            var cityID = 'city'+ Cities.cities[i].id;
             m += "<TD width=80><SPAN class=oohfancy>"+  Cities.cities[i].name.substring(0,10) +"</SPAN></td>";

        }
        m+="</tr>";
        var unitwounded = Seed.woundedUnits;
        for (var r=1; r<16; r++){
             m+='<tr><td><img height=18  title="'+unsafeWindow.unitcost['unt'+r][0]+'"  src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>&nbsp;'+unsafeWindow.unitcost['unt'+r][0]+'</td>';
            for(i=0; i<Cities.numCities; i++) {
                if (unitwounded) {
                    var a=unitwounded["city"+Cities.cities[i].id];
                    if (a) {
                        var nbunit=parseIntNan(a["unt"+r]);
                    }
                }
                m+="<td>"+addCommas(nbunit)+"</td>";
            }
            m+="</tr>";
        }
        // Reviving
         m +='<TR><TD  style="font-size:6px"><BR></td></tr><tr><td><img  height="18" src="'+URL_HOSPITAL+'"  title="'+culang.overviewHospitalNote+'"></b> #1</td>';
        for(i=0; i<Cities.numCities; i++) {
            var totTime = 0;
            var ah=Seed.queue_revive["city" + Cities.cities[i].id];
            var l=0;
            if (ah) {
                for(var an=0;an<Math.min(ah.length,1);an++){
                    var P=uW.unixtime();
                    l=parseInt(ah[an][3])-P;
                }
                var totTime = 0;
                totTime = parseIntNan(l);
                if (totTime < 0)
                    totTime = 0;
                affuichage = timestr(totTime);

                m +="<td><span>"+ affuichage + "</span></td>";

            } else {
                affuichage = timestr(totTime);

                m +="<td><span>"+affuichage+"</span></td>";
            }
            
        }
        m +="</tr>";
         m +='<TR><TD  style="font-size:6px"><BR></td></tr><tr><td><img  height="18" src="'+URL_HOSPITAL+'"  title="'+culang.overviewHospitalNote+'"></b> #2</td>';
        for(i=0; i<Cities.numCities; i++) {
            if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity && 
                  uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().ANCIENT_HEALING,  Cities.cities[i].id)) {
                var totTime = 0;
                var ah=Seed.queue_revive2["city" + Cities.cities[i].id];
                var l=0;
                if (ah) {
                    for(var an=0;an<Math.min(ah.length,1);an++){
                        var P=uW.unixtime();
                        l=parseInt(ah[an][3])-P;
                    }
                    var totTime = 0;
                    totTime = parseIntNan(l);
                    if (totTime < 0)
                        totTime = 0;
                    affuichage = timestr(totTime);

                    m +="<td><span>"+ affuichage + "</span></td>";

                } else {
                    affuichage = timestr(totTime);

                    m +="<td><span>"+affuichage+"</span></td>";
                }
            } else {
                m +="<td>---</td>";
            }
        }
        m +="</tr>";
        m+="</table>";
        $("KsApothecaryTroops").innerHTML=m;
    },

    e_addqueue : function (){
        var t = Tabs.Apothecary;
        var city = t.citysel.city.idx;
        var troopsel = $("pbapothecary_troops").value;
        var min = parseIntNan($("pbapothecary_min").value);
        var max = parseIntNan($("pbapothecary_max").value);
        var max_sel = $("pbapothecary_maxcheck").checked;
        try {
            if((troopsel < 1 || min < 1) || (max_sel && max < 1) || (max_sel && (max < min)))
                throw ""+culang.apothecaryIncompleteInput+"";
            ApothecaryOptions.city[city].push({troop:troopsel,min:min,max:max,max_sel:max_sel});
            saveApothecaryOptions();
            $('pbapothecary_options').style.background ='#99FF99';
            setTimeout(function(){ ($('pbapothecary_options').style.background =''); }, 1000);
        } catch (e){
            $('pbapothecary_options').style.background ='#FF0000';
            setTimeout(function(){ ($('pbapothecary_options').style.background =''); }, 1000);
        }
    },

    e_displayarray : function(){
        var t = Tabs.Apothecary;
        if(t.pop == null)
            t.pop = new CPopup('pbapothecary_pop',0,0,400,500,true,function(){t.pop.destroy(); t.pop = null;});
        t.pop.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.apothecaryAutoHealArray+'</div>';
        var m = '<div style="max-height:380px; height:380px; overflow-y:auto"><table class=pdxTab><tr>';
        for (var city in ApothecaryOptions.city){
            if(!Cities.cities[city] || ApothecaryOptions.city[city].length < 1) continue;
            m += '<td colspan=2><b>'+Cities.cities[city].name+'</b></td>\
              <td>'+culang.shortMin+'</td><td>'+culang.shortMax+'</td><tr>';
            for(var i=0; i<ApothecaryOptions.city[city].length; i++){
                var info = ApothecaryOptions.city[city][i];
                m += '<td>'+(i+1)+'</td><td>'+unsafeWindow.unitcost['unt'+info.troop][0]+'</td>\
                    <td>'+info.min+'</td><td>'+info.max+'</td><td>'+strButton20(''+culang.buttonEdit+'','title="'+culang.apothecaryEditNote+'"   onclick="pbapo(this,'+i+','+city+')"')+'</td><td>'+strButton20(''+culang.mainDelete+'','title="'+culang.apothecaryDeleteNote+'"  onclick="pbapo(this,'+i+','+city+')" ')+'</td>';
                m += '</tr><tr>';
            }
            m += '</tr><tr>';
        }
        t.pop.getMainDiv().innerHTML = m + "</table></div>";
        t.pop.show(true);
    },

    display_action : function(obj,id,city){
        var t = Tabs.Apothecary;
        var evt = null;
        if(obj.title == culang.apothecaryEditNote)
            evt = culang.apothecaryEditNote;
        if(obj.title == culang.apothecaryDeleteNote)
            evt = culang.apothecaryDeleteNote;
        if(evt == null || id == null) return;
        if(evt == culang.apothecaryDeleteNote){
            ApothecaryOptions.city[city].splice(id,1);
        }
        if(evt == culang.apothecaryEditNote){
            t.display_edit(id,city);
        }
        saveApothecaryOptions();
        t.e_displayarray();
    },

    display_edit : function(id, city){
        var t = Tabs.Apothecary;
        if(t.pop2 == null)
            t.pop2 = new CPopup('pbapodisp_pop',410,0,300,160,true,function(){t.pop2.destroy(); t.pop2 = null;});
        t.pop2.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.apothecaryAutoHealEditArray+'</div>';
         var m = '<table  class=pdxTab><tr><td><b>'+Cities.cities[city].name+'</b></td></tr>';
        var info = ApothecaryOptions.city[city][id];
         m += '<tr><td>'+culang.apothecaryTroopType+'  </td><td>'+unsafeWindow.unitcost['unt'+info.troop][0]+'</td></tr>\
           <tr><td>'+culang.shortMin+':  </td><td><INPUT id=pbapodisp_min type=text size=4  value="'+info.min+'" \>\
          <tr><td><INPUT  type=checkbox id=pbapodisp_maxcheck '+(info.max_sel?'CHECKED':'')+'  /> '+culang.shortMax+': </td><td><INPUT  id=pbapodisp_max type=text size=4 value="'+info.max+'"  '+(info.max_sel?'':'DISABLED')+' \></td></tr>\
           <tr><td><INPUT type=submit id=pbapodisp_save  value="'+culang.buttonSave+'" /></td></tr>';
        t.pop2.getMainDiv().innerHTML = m;
        t.pop2.show(true);
        $('pbapodisp_save').addEventListener('click', function(){
            var min = parseIntNan($("pbapodisp_min").value);
            var max = parseIntNan($("pbapodisp_max").value);
            var max_sel = $("pbapodisp_maxcheck").checked;
            if(min < 1 || (max_sel && max < 1) || (max_sel && (max < min))){
                alert(culang.apothecaryIncorrectInput);
                return;
            }
            info.min = min;
            info.max = max;
            info.max_sel = max_sel;
            saveApothecaryOptions();
            t.pop2.show(false);
            t.e_displayarray();
        },false);
    },

    loop : function(){
        var t = Tabs.Apothecary;
        var now = unixTime();
        clearTimeout(t.timer);
        //Warteschlangen leeren
        for (var h in Seed.queue_revive) {
            var e = Seed.queue_revive[h];
            if (e.length > 0 && e[0][3] < now) {
                Seed.queue_revive[h] = [];
            }
        }
        for (var h in Seed.queue_revive2) {
            var e = Seed.queue_revive2[h];
            if (e.length > 0 && e[0][3] < now) {
                Seed.queue_revive2[h] = [];
            }
        }
        if(!ApothecaryOptions.Active) return;
        for (var city in ApothecaryOptions.city){
            if(!Cities.cities[city] || ApothecaryOptions.city[city].length < 1) continue;
            if(t.cities[city]) continue; //Skip if Apothecary doesn't exist
             var r =  uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().ANCIENT_HEALING,  Cities.cities[city].id);
            if (r) {
                 if(Seed.queue_revive['city'+Cities.cities[city].id].length > 0  && Seed.queue_revive2['city'+Cities.cities[city].id].length >  0) continue; //Skip city if queue & queue2 are full
            } else {
                 if(Seed.queue_revive['city'+Cities.cities[city].id].length  > 0) continue; //Skip city if queue is full        
            }
             if(Seed.citystats["city" + Cities.cities[city].id].gold[0]  < parseInt(ApothecaryOptions.goldkeep)) continue; //Skip if gold is  less than reserve
            for(var i=0; i<ApothecaryOptions.city[city].length; i++){
                var info = ApothecaryOptions.city[city][i];
                var cid = Cities.cities[city].id;
                var amt = 0;
                if(Seed.woundedUnits['city'+cid]['unt'+info.troop] < info.min) continue;
                if(Seed.woundedUnits['city'+cid]['unt'+info.troop] > info.max && info.max_sel){
                    amt = info.max;
                } else {
                    amt = Seed.woundedUnits['city'+cid]['unt'+info.troop];
                }
                if(cid > 0 && info.troop > 0 && amt > 0){
                    var c = uW.cm.WorldSettings.getSettingAsObject("APOTHECARY_COST");
                    var cost = c[info.troop]["Cost"] * amt;
                    if (parseInt(Seed.citystats["city" + cid].gold[0]) > cost) {
                        t.do_revive(cid,info.troop,amt);
                        break;
                    }
                }
            }
        }
        t.timer = setTimeout(t.loop, 10000);
    },

    e_toggleswitch : function(obj){
        var t = Tabs.Apothecary;
        if(ApothecaryOptions.Active){
            obj.value = culang.apothecaryAutoHeal+' = '+culang.buttonOFF;
            ApothecaryOptions.Active = false;
            clearTimeout(t.timer);
        } else {
            obj.value = culang.apothecaryAutoHeal+' = '+culang.buttonON;
            ApothecaryOptions.Active = true;
            t.timer = setTimeout(t.loop,5000);
        }
        saveApothecaryOptions();
    },

    do_revive : function(currentcityid,unitId,num,notify){
        var t = Tabs.Apothecary;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = currentcityid;
        params.type = unitId;
        params.quant = num;
        params.apothecary = true;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function(rslt) {
                if (rslt.ok) {
                    for (var i = 1; i < 5; i++) {
                        var resourceLost = parseInt(unsafeWindow.unitcost["unt" + unitId][i]) * 3600 * parseInt(num);
                        if(rslt.gamble) resourceLost = resourceLost*rslt.gamble[i];
                         Seed.resources["city" + currentcityid]["rec" +  i][0] = parseInt(unsafeWindow.seed.resources["city" +  currentcityid]["rec" + i][0]) - resourceLost;
                    }
                    if (!rslt.initTS) {
                        rslt.initTS = unixTime() - 1;
                    }
                    if (Seed.queue_revive["city" + currentcityid].length == 0) {
                        var q = Seed.queue_revive["city" + currentcityid];
                        var c = rslt.queue_revive['city' + currentcityid][0];
                    } else {
                        var q = Seed.queue_revive2["city" + currentcityid];
                        var c = rslt.queue_revive2['city' + currentcityid][0];
                    }
                    q.push(c);
                    var c = uW.cm.WorldSettings.getSettingAsObject("APOTHECARY_COST");
                    var cost = c[unitId]["Cost"] * num;
                    Seed.citystats["city" + currentcityid].gold[0] -= parseInt(cost);
                    unsafeWindow.update_gold();
                     Seed.woundedUnits["city" + currentcityid]["unt" +  unitId] = parseInt(Seed.woundedUnits["city" + currentcityid]["unt" +  unitId]) - parseInt(num);
                    var rep = {
                        'num' : num,
                        'unit' : uW.unitcost['unt'+unitId][0],
                        'city' : Cities.byID[currentcityid].name,
                    };
                    actionLog(culang.mainApo, culang.mainApoOK.mreplace(rep));
                } else {
                    var rep = {
                        'num' : num,
                        'unit' : unsafeWindow.unitcost['unt'+unitId][0],
                        'city' : Cities.byID[currentcityid].name,
                        'error' : uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)),
                    };
                    actionLog(culang.mainApo, culang.mainApoError.mreplace(rep));
                }
            },
            onFailure: function (rslt) {
                actionLog(culang.mainApo, culang.mainApoFatalError);
            },
        });
    },
    
    hide : function (){
        var t = Tabs.Apothecary;
        clearInterval(t.timerStat);
    },

    show : function (){
        var t = Tabs.Apothecary;
        t.timerStat = setInterval(t.displayStat,10000);
    },


};
/************************************************************************************
*                        KOC POWER - TABS PLAYER                                        *
************************************************************************************/
Tabs.AllianceList = { //TODO rename? to Player
    tabOrder: TabOptions.toPlayer,
    tabLabel: culang.mainPlayer,
    cont : null,
    nombre: null,
    state : null,
    dat : [],

    show : function (){
    },

    hide : function (){
    },

    init : function (div){
        var t = Tabs.AllianceList;
        t.cont = div;
        t.nombre=0;
        uW.BoPTgetMembers = t.eventGetMembers;
        uW.PTPaintMembers = t.GetDataForMap;
        uW.BoPTDme = t.eventGetLienMember;
        uW.BoPTpd = t.clickedPlayerDetail;
        uW.BoPTpl = t.clickedPlayerLeaderboard;
        uW.BoPTpl2 = t.clickedPlayerLeaderboard2;
        uW.BoPCplo = t.clickedPlayerGetLastLogin;
        uW.BoPTalClickPrev = t.eventListPrev;
        uW.BoPTalClickNext = t.eventListNext;

        if (t.state == null){
            if (getMyAlliance()[0] == 0) {
                 t.cont.innerHTML =  '<BR><CENTER><i><b>'+culang.playerMustInAlliance+'</i></b></center>';
                t.state = 1;
                return;
            }
            var m = '<DIV class=pdxEntry><TABLE width=100% cellpadding=0>\
           <TR><TD class=xtab align=right></td><TD  class=xtab>'+culang.playerName+' &nbsp;</td>\
             <TD width=80% class=xtab><INPUT id=allPlayName size=20  type="text"> &nbsp; <INPUT id=playSubmit type=submit  value="'+culang.playerSearchPlayer+'" /></td>\
            <TD width=100% class="xtab ptErrText"><SPAN id=ptplayErr></span></td></tr>\
           <TR><TD class=xtab>&nbsp;</td><TD  class=xtab>'+culang.playerAlliance+' &nbsp;</td>\
             <TD class=xtab><INPUT id=allAllName type=text /> &nbsp;  <INPUT id=allSubmit type=submit  value="'+culang.playerSearchAlliance+'" /></td>\
            <TD class="xtab ptErrText"><SPAN id=ptallErr></span></td></tr>\
            <TR><TD class=xtab>&nbsp;</td><TD class=xtab> &nbsp;\
            <INPUT align=left id=allListSubmit type=submit value="'+culang.playerSearchAllianceList+'" /></td>\
            <TD class=xtab><INPUT align=right id=allGotoPage type=submit value="'+culang.mainPage+'" />\
             <INPUT align=right id=idPageNum type="text" value='+t.curPage+' size=4 />\
             <INPUT align=left id="idMyAllSubmit" type=submit value="'+ getMyAlliance()[1] +'"/>\
             <INPUT align=left id="idMyTHSubmit" type=submit value="'+culang.playerTop100+'"/></td></tr>\
           </table><TABLE width=100% cellpadding=0  class="pdxTab"><tr><td><span  style="vertical-align:middle;" id=altInput></span></td>\
          <td><div><select id="idFindETASelect">\
                 <option value="0" >-- '+culang.mainSelect+' --</option>\
     <option value="1" >'+unsafeWindow.unitcost["unt1"][0]+'</option>\
        <option value="2" > '+unsafeWindow.unitcost["unt2"][0]+' </option>\
        <option value="3" > '+unsafeWindow.unitcost["unt3"][0]+' </option>\
        <option value="4" > '+unsafeWindow.unitcost["unt4"][0]+' </option>\
        <option value="5" > '+unsafeWindow.unitcost["unt5"][0]+' </option>\
        <option value="6" > '+unsafeWindow.unitcost["unt6"][0]+' </option>\
        <option value="7" > '+unsafeWindow.unitcost["unt7"][0]+' </option>\
        <option value="8" > '+unsafeWindow.unitcost["unt8"][0]+' </option>\
        <option value="9" > '+unsafeWindow.unitcost["unt9"][0]+' </option>\
        <option value="10" > '+unsafeWindow.unitcost["unt10"][0]+' </option>\
        <option value="11" > '+unsafeWindow.unitcost["unt11"][0]+' </option>\
        <option value="12" > '+unsafeWindow.unitcost["unt12"][0]+' </option>\
        </select></div></td></tr></table>\
        </div>\
          <SPAN id=allListOut></span>';
            t.cont.innerHTML = m;

            ById('allSubmit').addEventListener ('click', t.eventSubmit, false);
            ById('playSubmit').addEventListener ('click', t.eventPlayerSubmit, false);
            ById('allAllName').addEventListener ('focus', function (){ById('ptallErr').innerHTML='';}, false);
            ById('idMyTHSubmit').addEventListener ('click', t.eventListTHSubmit, false);
            ById('allPlayName').addEventListener ('focus', function (){ById('ptplayErr').innerHTML='';}, false);
            ById('allListSubmit').addEventListener ('click', t.eventListSubmit, false);
            ById('allGotoPage').addEventListener ('click', t.gotoPage, false);
            ById('idMyAllSubmit').addEventListener ('click', t.showMyAlliance, false);
            ById('allGotoPage').disabled = true;
            ById('idFindETASelect').addEventListener ('click', t.handleEtaSelect, false);
            ById('idFindETASelect').disabled = true;

            t.ModelCity=Cities.cities[0];
            t.curPage = 0;
            t.MaxPage = -1;
            t.state = 1;
        }
    },

    pName : '',
    eventPlayerSubmit : function (){
        var t = Tabs.AllianceList;
        ById('ptplayErr').innerHTML='';
        var name = ById('allPlayName').value;
        name = name.replace(/\'/g,"_");
        t.pName = name;
        if (name.length < 3){
            ById('ptplayErr').innerHTML = culang.playerMinSearch;
            return;
        }
        ById('altInput').innerHTML = '';
         ById('allListOut').innerHTML =  '<BR><CENTER><i><b>'+culang.playerLoading+'</b></i></center>';
        t.fetchPlayerList (name, t.eventGotPlayerList);
    },
    eventGetLienMember: function(name) {
        var t = Tabs.AllianceList;
        ById('allPlayName').value = name;
        t.eventPlayerSubmit();
    },
    eventGotPlayerList : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }
        t.playerList = rslt.matchedUsers;
        var uList = [];
        for (k in rslt.matchedUsers)
            uList.push (rslt.matchedUsers[k].userId);
        t.fetchPlayerStatus (uList, function(r) {t.eventGotPlayerOnlineList(r)});
    },

    eventGotPlayerOnlineList : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }
        var m = '<DIV class=pdxStat>'+culang.playerSearchPlayerHead+' <b>"'+ t.pName +'"</b></div>\
      <DIV style="max-height:575px;">\
       <TABLE width=95% align=center class=pdxTab cellspacing=0><TR  style="font-weight:bold"><TD  width=20%>'+culang.mainPlayer+'</td>\
      <TD  align=right>'+uW.g_js_strings.commonstr.might+'  &nbsp;&nbsp;&nbsp;&nbsp;</td><TD>'+culang.mainOnline+'</td><TD  width=60%>'+culang.mainInfo+'</td></tr>';
        var row=0;
        var cl='';
        for (k in t.playerList){
            var u = t.playerList[k];
            if (++row % 2)
                cl = 'class=ptOddrow ';
            else
                cl = '';
            if (u.allianceName) { var alliancenammme=u.allianceName; }else {var alliancenammme="---"; }
             m += '<TR '+ cl +'valign=top><TD><A  target="_tab"  href="http://koc.dunno.com/index.sjs?f=ServersByUser&user_id='+  u.userId +'" title="'+culang.playerSearchPlayerKoCdunnoNote+'">'+  u.genderAndName +'</a><br> <a target="_tab"  href="http://kocmon.com/'+getServerId()+'/alliances/'+ u.allianceId +'"  title="'+culang.playerSearchAllianceKoCMonNote+'">'+alliancenammme+'</a><br><A  target="_tab" href="http://www.facebook.com/profile.php?id='+ u.fbuid  +'">'+culang.mainFacebook+'</a><BR>'+culang.playerSearchPlayerUserID+'  '+ u.userId +'<BR><a target="_tab"  href="http://kocmon.com/'+unsafeWindow.domainName +'/players/'+ u.userId  +'"  title="'+culang.playerSearchPlayerKoCMonNote+'">'+culang.playerSearchPlayerKoCMon+'</a></td><TD  align=center>&nbsp;'+ addCommasInt(u.might)  +'&nbsp;</td>\
          <TD>'+  (rslt.data[u.userId]?"&nbsp;<SPAN  class=boldDarkRed>"+culang.mainOnline+"</span>":"")  +'</td>\
         <TD><SPAN onclick="BoPTpd(this, '+  u.userId +')"><A>'+culang.searchDetails+'</a> &nbsp;  <BR></span><span onclick="BoPTpl2(this,'+  u.userId+','+rslt.data[u.userId]+')"><A>'+uW.g_js_strings.modaltitles.leaderboard+'</a></span>&nbsp;<br><SPAN  onclick="BoPCplo(this, \''+ u.userId  +'\')"><A>'+culang.mainLastLogin+'</a></span></td></tr>';
        }
        m += '</table></div>';
        ById('allListOut').innerHTML = m;
    },

    clickedPlayerDetail : function (span, uid){
        var t = Tabs.AllianceList;
        span.onclick = '';
        span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.memberdetails + " ...";
        t.fetchPlayerInfo (uid, function (r) {t.gotPlayerDetail(r, span)});
    },

    clickedPlayerLeaderboard : function (span, uid){
        var t = Tabs.AllianceList;
        span.onclick = '';
        span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.leaderboard + " ...";
        t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard(r, span)});
    },
    clickedPlayerLeaderboard2 : function (span, uid,status){
        var t = Tabs.AllianceList;
        span.onclick = '';
        span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.leaderboard + " ...";
        t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard2(r, span,uid,status)});
    },

    clickedPlayerGetLastLogin : function (span, uid){
        var t = Tabs.AllianceList;
        span.onclick = '';
         span.innerHTML = uW.g_js_strings.commonstr.search +': '+  uW.g_js_strings.modal_messages_viewreports_view.lastlogin + " ...";
        t.fetchPlayerLastLogin (uid, function (r) {t.gotPlayerLastLogin(r, span)});
    },
    gotPlayerLeaderboard2 : function (rslt,span,uid,status){
        var t = Tabs.AllianceList;

        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }
        if (rslt.totalResults == 0){
             span.innerHTML =  '<B>'+uW.g_js_strings.commonstr.leaderboard+':  </b>'+uW.itemlist.i10021.name+'?<BR>';
            return;
        }
        var myA = getMyAlliance ();
        t.dat = [];
        var p = rslt.results[0];
        if ( myA[0] == p.allianceId)
            t.friendEta = true;
        else
            t.friendEta = false;
        for (var c=0; c<p.cities.length; c++){
             t.dat.push ([p.displayName, parseInt(p.might), p.officerType,  parseInt(p.numCities), parseInt(p.cities[c].tileLevel),
                 parseInt(p.cities[c].xCoord), parseInt(p.cities[c].yCoord),  p.cities[c].cityName, 0, c, p.userId, p.avatarId, p.playerSex, p.rank,  status, ''+culang.shortNotAvailable+'']);

        }
        t.setDistances (Cities.cities[0].x, Cities.cities[0].y);
        t.ModelCity=Cities.cities[0];
        t.setEta();
        t.fetchPlayerLastLogin (uid, function (r) {t.displayPlayer(p.allianceName,r)});

    },
    gotPlayerLeaderboard : function (rslt, span){
        var t = Tabs.AllianceList;

        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }
        if (rslt.totalResults == 0){
             span.innerHTML =   '<B>'+uW.g_js_strings.commonstr.leaderboard+':  </b>'+uW.itemlist.i10021.name+'?<BR>';
            return;
        }
        var p = rslt.results[0];
        var an = p.allianceName;
        if (!an || an=='' || p.officerType==4)
            an = ''+culang.mainNone+'';
        else
            an += ' ('+ officerId2String(p.officerType) +')';
         m = '<TABLE cellspacing=0  class=pdxTab><TR><TD><B>'+uW.g_js_strings.commonstr.leaderboard+':  </b></td><TD colspan=2>  '+uW.g_js_strings.commonstr.might+': '+ p.might  +' &nbsp;  '+uW.g_js_strings.commonstr.alliance+': '+ an +'</td></tr>';
        for (var i=0; i<p.cities.length; i++){
            var c = p.cities[i];
            var created = '';
            if (c.dateCreated && c.dateCreated.substr(0,2)=='20')
                created = ' &nbsp; &nbsp; '+culang.mainCreate+': ' + c.dateCreated.substr(0,10);
             m += '<TR><TD  align=right><B>'+culang.mainCity+' #'+ (i+1)  +':</b></td><TD> &nbsp; '+ c.cityName
                 + '&nbsp;<a href="javascript:void(0)"  onclick="cm.utils.CoordinateLinkController.onClick(event)"  class="coordinateLink">('+ c.xCoord +',' +c.yCoord+ ')</a>'
                + '</td><TD width=75%> &nbsp; '+uW.g_js_strings.commonstr.level+' : '
                 + c.tileLevel +' &nbsp; &nbsp;  '+culang.mainStatus+': '+ cityStatusString (c.cityStatus) + created  +'</td></tr>';
        }
        span.innerHTML = m + '</table>';

    },
    displayPlayer : function (allName,rslt){
        var t = Tabs.AllianceList;
        function alClickSort (e){
            var t = Tabs.AllianceList;
            var newColNum = e.id.substr(8);
            ById('clickCol'+t.sortColNum).className = 'clickable';
            e.className='clickable clickableSel';
            if (newColNum == t.sortColNum)
                t.sortDir *= -1;
            else
                t.sortColNum = newColNum;
            t.reDisp();
        }
        unsafeWindow.PTalClickSort = alClickSort;
         var m = '<STYLE>.clickable{background-color:#ddd; border:2px  outset; border-color:#555; padding-left:5px; padding-right:5px}\
            .clickableSel{background-color:#ffffcc;}\
            .xxtab{background-color:none; padding-left:5px; padding-right:5px;} </style>\
             <DIV class=pdxStat ><TABLE id=tabAllMembers cellpadding=0   width=100%><TR font-weight:bold"><TD  class=xtab>'+uW.g_js_strings.commonstr.alliance+': '+ allName  +'</td>\
              <TD class=xtab width=80%  align=center>'+culang.mainLastLogin+': <SPAN id=lastlogin>'+   rslt.playerInfo.lastLogin+'</span></td><TD class=xtab  align=right></td></tr></table></div>\
       <div style="max-height:470px; "><TABLE id=tabAllMembers  align=center cellpadding=0 cellspacing=0><THEAD >\
       <TR style="font-weight:bold"><TD id=clickCol0  onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainPlayer+'</div></a></td>\
         <TD id=clickCol1 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+culang.mainRank+'</a></div></td>\
         <TD id=clickCol3 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainCities+'</a></div></td>\
         <TD id=clickCol2 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+uW.g_js_strings.commonstr.alliance+'</a></div></td>\
         <TD id=clickCol9 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+culang.mainOnline+'</a></div></td>\
         <TD id=clickCol7 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainCity+'</a></div></td>\
         <TD id=clickCol4 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.shortLevel+'</a></div></td>\
         <TD id=clickCol5 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.shortCoordinate+'</a></div></td>\
         <TD id=clickCol8 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainDistance+  '</a></div></td>\
        <TD id=clickCol10  onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainArrival+'</a></div></td>\
         <TD  class=clickable><A><DIV>'+culang.mainLogin+'</a></div></td></tr></thead>\
      <TBODY id=allBody style="background-color:#ffffff; min-height:600px;"></tbody></table></div>\
       <DIV  width:100%; style="top:670px; left:0px; position:absolute;  background-color:#ffffff; border-top:1px solid; margin-top:8px;  color:#700; font-weight:bold;">';
        ById('allListOut').innerHTML = m;
        ById('altInput').innerHTML = '<TABLE width=100% cellpaddding=0><TR align=center>\
         <TD class=xtab>'+culang.playerSearchHead+': &nbsp; X:  <INPUT size=2 type=text id=plyrX /> Y: <INPUT size=2 type=text  id=plyrY /> &nbsp;<span  id=dmcoords></span></td></tr></table>';
        ById('clickCol'+t.sortColNum).className = 'clickable clickableSel';

        t.reDisp();
        new CdispCityPicker ('plyrdcp', ById ('dmcoords'), true, t.eventCoords, 0).bindToXYboxes(ById('plyrX'), ById('plyrY'));
        ById('idFindETASelect').disabled = false;
    },

    gotPlayerLastLogin : function (rslt, span){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }

        var p = rslt.playerInfo;
        var lastLogin = rslt.playerInfo.lastLogin;

        if (lastLogin) {
            m = '<span style="color:blue">'+lastLogin+'</span>';
        } else {
            m = '<span style="color:red">-</span>';
        }
        span.innerHTML = m + '';
    },
    gotPlayerDetail : function (rslt, span){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }
        var u = rslt.userInfo[0];
        var a = ''+culang.mainNone+'';
        if (u.allianceName)
            a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
         var m = '<TABLE cellspacing=0  class=pdxTab><TR><TD><B>'+culang.searchDetails+':</b>  &nbsp; </td><TD>'+uW.g_js_strings.commonstr.alliance+':  '+ a +' &nbsp; '+culang.mainCities+': ' + u.cities +' &nbsp;  '+culang.mainPopulation+': '+ u.population  +'</td></tr><TR><TD></td><TD>'+culang.mainProvinces+':  ';
        var pids = u.provinceIds.split (',');
        var p = [];
        for (var i=0; i<pids.length; i++)
            p.push(unsafeWindow.provincenames['p'+pids[i]]);
        span.innerHTML = m + p.join (', ') +'</td></tr></table>';
    },

    aName : '',
    eventSubmit : function (){
        var t = Tabs.AllianceList;
        ById('ptallErr').innerHTML='';
        t.aName = ById('allAllName').value;
        if (t.aName.length < 3){
            ById('ptallErr').innerHTML = uW.g_js_strings.getAllianceSearchResults.entryatleast3;
            return;
        }
        var myA = getMyAlliance ();
        ById('altInput').innerHTML = '';
        ById('allListOut').innerHTML = '<BR><BR><CENTER>'+culang.playerLoading+'</center>';
        if (myA[0]!=0 && myA[1].toLowerCase().indexOf(t.aName.toLowerCase())>=0 )
            t.fetchAllianceList (t.aName, myA[0], t.eventGotAllianceList);
        else
            t.fetchAllianceList (t.aName, null, t.eventGotAllianceList);
    },
    eventListSubmit : function (){
        var t = Tabs.AllianceList;
        var myA = getMyAlliance ();
        ById('allListOut').innerHTML = '<BR><BR><CENTER>'+culang.playerLoading+'</center>';
        if (myA[0]!=0  ) {
            t.curPage=1;
            t.fetchOtherAllianceInfo ( 1, t.eventGotOtherAlliancePage);
            ById('allGotoPage').disabled = false;
        }
        else {
            ById('allListOut').innerHTML =  culang.playerMustInAlliance;
        }
    },
    eventListTHSubmit : function (){
        var t = Tabs.AllianceList;
         ById('allListOut').innerHTML =  '<BR><CENTER><i><b>'+culang.playerTop100Search+'</b></i></center>';
        t.fetchUserLeaderboard (1, t.eventGetUserLeaderboard);
    },
    eventGotAllianceList : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }
        var m = '<DIV class=pdxStat>'+culang.playerSearchAllianceHead+' <B>"'+ t.aName +'"</b></div>\
     <TABLE><TR style="font-weight:bold"><TD  class=xtab>'+unsafeWindow.g_js_strings.commonstr.alliance+'</td><TD  class=xtab>'+culang.mainRank+'</td><TD  class=xtab>'+culang.mainPlayer+'</td>\
        <TD  align=right  class=xtab>'+unsafeWindow.g_js_strings.commonstr.might+'</td><TD  class=xtab>'+culang.mainDiplo+'</td><TD  class=xtab>'+culang.mainPlayer+'</td><TD  class=xtab>'+culang.mainMap+'</td></tr>';
        for (k in rslt.alliancesMatched){
            var all = rslt.alliancesMatched[k];
            var dip = '';
            if (all.relation && all.relation==1)
                dip = ''+culang.kocFriendly+'';
            else if (all.relation && all.relation==2)
                dip = ''+culang.kocHostile+'';
             m += '<TR  class="'+ dip + '"><TD class=xtab>'+  all.allianceName +'</td><TD align=right class=xtab>'+  all.ranking +'</td><TD align=right class=xtab>'+  all.membersCount +'</td>\
       <TD align=right class=xtab>'+ addCommasInt(all.might) +'</td><TD class=xtab>'+ dip +'</td>\
       <TD class=xtab><a onclick="BoPTgetMembers('+ all.allianceId +')">'+culang.mainPlayer+'</a></td>\
        <TD class=xtab><a onclick="PTPaintMembers('+ all.allianceId  +')">'+culang.mainMap+'</a></td></tr>';
        }
        ById('allListOut').innerHTML = m;
    },
    GetDataForMap : function (allianceId) {
        var t = Tabs.AllianceList;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        var Data=[];
        params.perPage = 100;
    params.type = 'might';
    params.page = 1;
        params.allianceId = allianceId;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                var city = '';
                for (var i=0; i<rslt.results.length; i++) {
                    if (rslt.results[i]['userId'] !=0){
                        player = rslt.results[i]['cities'];
                        for (var ii=0; ii<player.length; ii++)
                            Data.push ({X:player[ii]['xCoord'],Y:player[ii]['yCoord']});
                    }
                }
                if (Data != []) t.PaintDataOnMap(Data);
            },
            onFailure: function (rslt) {
                notify ({errorMsg:'AJAX error'});
            },
        });
    },
    PaintDataOnMap : function(Data){
        var provMapCoordsA = {imgWidth:710, imgHeight:708, mapWidth:670, mapHeight:670, leftMargin:31, topMargin:19};
         var map = '<div style="overflow:auto;  max-height:'+(Options.HauteurBoite-140)+'px;"><DIV  id=ptAlliProvMap style="height:'+ provMapCoordsA.imgHeight +'px;  width:'+ provMapCoordsA.imgWidth +'px; background-repeat:no-repeat;  background-image:url(\''+ URL_PROVINCE_MAP  +'\')"></div></div>';
        ById('allListOut').innerHTML = map;
        var eMap =  ById('ptAlliProvMap');
        for (var cc=0; cc<Seed.cities.length; cc++) {
            var city = Seed.cities;
            var Xplot = parseInt((provMapCoordsA.mapWidth * parseInt(city[cc][2])) / 750);
            var Yplot = parseInt((provMapCoordsA.mapHeight * parseInt(city[cc][3])) / 750);
            var cf = document.createElement ('div');
            cf.style.background = 'black';
            cf.style.opacity = '1.0';
            cf.style.position='relative';
            cf.style.display='block';
            cf.style.width='14px';
            cf.style.height='16px';
            cf.style.border='1px solid #fff';
            cf.style.color = 'white';
            cf.style.textAlign = 'center';
            cf.style.top = (Yplot+provMapCoordsA.topMargin-(cc*16)-8) +'px';
            cf.style.left = (Xplot+provMapCoordsA.leftMargin-7) +'px';
            cf.innerHTML = (cc+1) +'';
            eMap.appendChild(cf);

        }
        for (var i=0;i<Data.length;i++) {
            var x = parseInt(Data[i]['X']);
            var y = parseInt(Data[i]['Y']);
            var xplot = parseInt((provMapCoordsA.mapWidth * x) / 750);
            var yplot = parseInt((provMapCoordsA.mapHeight * y) / 750);
            var ce= document.createElement ('div');
            ce.style.background = 'red';
            ce.style.opacity = '1.0';
            ce.style.position='relative';
            ce.style.display='block';
            ce.style.width='4px';
            ce.style.height='4px';
            ce.style.color = 'white';
            ce.style.textAlign = 'center';
            ce.style.top = (yplot+provMapCoordsA.topMargin -(4*i)-((Seed.cities.length)*18)) +'px';
            ce.style.left = (xplot+provMapCoordsA.leftMargin -2) +'px';
            ce.innerHTML = '<DIV onclick="ptGotoMap('+ x +','+ y +')">&nbsp;</div>';
            eMap.appendChild(ce);
        }
    },
    showMyAlliance : function (){
        var t = Tabs.AllianceList;
        var myA = getMyAlliance ();
        ById('allListOut').innerHTML = '<BR><BR><CENTER>'+culang.playerLoading+'</center>';
        if (myA[0]!=0  ) {
            t.eventGetMembers(myA[0]);
        }
        else {
            ById('allListOut').innerHTML =  culang.playerMustInAlliance;
        }
    },
    curPage : 0,
    MaxPage : 0,

    eventListNext : function (amt){
        var t = Tabs.AllianceList;
        if( parseInt(amt) >= 9999 )
            t.curPage = t.MaxPage;
        else {
            t.curPage = parseInt(t.curPage) + parseInt(amt);
            if ( t.curPage > t.MaxPage) {
                t.curPage = t.MaxPage;
            }
        }
        ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
        t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
    },

    eventListPrev : function (amt){
        var t = Tabs.AllianceList;
        if(amt <= -1)
            t.curPage = 1;
        else {
            t.curPage-=amt;
            if ( t.curPage < 1 ) {
                t.curPage = 1;
            }
        }
        ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
        t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
    },

    gotoPage : function (){
        var t = Tabs.AllianceList;
        var val = ById('idPageNum').value;
        if (t.MaxPage < 0 ) {
            ById('allListOut').innerHTML = ''+culang.playerListAlliancesFirst+'';
            return;
        }
        if (t.MaxPage < 0 || val > t.MaxPage || val < 1) {
            ById('allListOut').innerHTML = ''+culang.playerPageOutOfRange+'';
            return;
        }
        t.curPage = val;
        ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
        t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
    },

    eventGetUserLeaderboard: function(rslt) {
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }
         var m = '<div  style="max-height:'+(Options.HauteurBoite-190)+'px;  overflow:auto;"><div  class="pdxStat">'+culang.playerTop100Head+'  '+getServerId()+'</div> <TABLE  width="100%"><thead><TR style="font-weight:bold"> \
           <th class=xtab>'+culang.mainRank+'</th><th class=xtab  style="width:60px;">'+culang.mainAvatar+'</th><th>'+culang.mainName+'</th><th  class=xtab>'+uW.g_js_strings.commonstr.might+'</th>\
           <th  class=xtab>'+uW.g_js_strings.commonstr.alliance+'</th><th  class=xtab>'+culang.mainPosition+'</th><th  class=xtab>'+culang.mainCities+'</th></tr></thead><tbody>';
        ById('allListOut').innerHTML = m;
        for (var i=0; i<rslt.results.length; i++) {
            var resultat = rslt.results[i];

            m += '<TR class=xtab><TD class=xtab align=center><b>' + resultat.rank +'</b></td>\
                 <td class=xtab><center><img  src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/avatars/v2/25/'  + resultat.playerSex.toLowerCase()+ '' + resultat.avatarId +  '.png"></center></td>\
             <TD  class=xtab><a onclick=BoPTDme("' + resultat.displayName +'");  title="'+culang.playerShowNote+' ' + resultat.displayName +'  '+culang.playerShowNote2+'">' + resultat.displayName  +'</a></td>\
             <td class=xtab>' + resultat.might + '</td>\
              <td class=xtab><a onclick="BoPTgetMembers('+  resultat.allianceId +')" title="'+culang.playerShowNote+' ' +  resultat.allianceName + ' '+culang.playerShowNote2+'">' +  resultat.allianceName + '</a></td>\
             <td  class=xtab>' + officerId2String(resultat.officerType) +  '</td><td class=xtab>' + resultat.numCities + '</td>\
             </tr>';
            m += '</div>';
            ById('allListOut').innerHTML = m;
        }
    },
    fetchUserLeaderboard: function(pagNum, notify) {
        var t = Tabs.AllianceList;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.page = pagNum;
        params.perPage = 100;
    params.type = 'might';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify (rslt);
            },
        });
    },


    eventGotOtherAlliancePage : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }

        ById('idPageNum').value = t.curPage;

        t.MaxPage=rslt.noOfPages;

         var m = '<div  style="max-height:'+(Options.HauteurBoite-200)+'px;width:95%;"><TABLE><thead><TR  style="font-weight:bold"> \
   <th  class=xtab>'+culang.mainRank+'</th><th  class=xtab>'+uW.g_js_strings.modaltitles.alliance+'</th><th  class=xtab>'+uW.g_js_strings.commonstr.chancellor+'</th><th  class=xtab>'+culang.mainPlayer+'</th>\
        <th  align=right  class=xtab>'+uW.g_js_strings.commonstr.might+'</th><th  align=right  class=xtab>'+uW.g_js_strings.commonstr.glory+'</th><th  class=xtab>'+culang.mainDiplo+'</th><th  class=xtab>'+culang.mainPlayer+'</th><th  class=xtab>'+culang.mainMap+'</th></tr></thead><tbody>';
        ById('allListOut').innerHTML = m;

        for (var i=0; i<rslt.otherAlliances.length; i++) {
            var alliance = rslt.otherAlliances[i];
            var dip = '';
            dip = getDiplomacy(alliance.allianceId);

             m += '<TR class="'+ dip + '"><TD align=right  class=xtab>'+ alliance.ranking +'</td><TD class=xtab>' +  alliance.name +'</td><TD class=xtab>' +  alliance.hostGenderAndName +'</td><TD align=right  class=xtab>'+ alliance.membersCount +'</td>\
       <TD  align=right class=xtab>'+ addCommasInt(alliance.might)  +'</td><TD align=right class=xtab>'+  addCommasInt(alliance.glory) +'</td><TD class=xtab>'+ dip  +'</td>\
       <TD class=xtab><a  onclick="BoPTgetMembers('+ alliance.allianceId  +')">'+culang.mainPlayer+'</a></td>\
       <TD  class=xtab><a onclick="PTPaintMembers('+ alliance.allianceId  +')">'+culang.mainMap+'</a></td></tr>';
        }
         m += '</tbody></TABLE><div  style="font-weight:bold;width:95%;text-align:center;"><span><center><a  onclick="BoPTalClickPrev(-1)"> <img src="'+IMGfirstPage+'"  title="'+culang.playerSearchFirstPageNote+'" > </a><a  onclick="BoPTalClickPrev(10)"> <img src="'+IMGback10+'"  title="-10"> </a><a onclick="BoPTalClickPrev(5)"> <img  src="'+IMGback5+'" title="-5"> </a><a  onclick="BoPTalClickPrev(1)"> <img src="'+IMGback+'"  title="'+culang.playerSearchBackNote+'" </a>  <a  onclick="BoPTalClickNext(1)"> <img src="'+IMGnext+'"  title="'+culang.playerSearchNextNote+'"> </a><a  onclick="BoPTalClickNext(5)"> <img src="'+IMGnext5+'"  title="+5"> </a><a onclick="BoPTalClickNext(10)"> <img  src="'+IMGnext10+'" title="+10"> </a><a  onclick="BoPTalClickNext(9999)"> <img src="'+IMGlastPage+'"  title="'+culang.playerSearchLastPageNote+'"> </a>  </span></div>';
        m += '</div>';

        ById('allListOut').innerHTML = m;
    },

    showCurrentPage : function (){
        var t = Tabs.AllianceList;
        var myA = getMyAlliance ();

         ById('allListOut').innerHTML =  '<BR><CENTER><i><b>'+culang.playerPageDisplay+'</b></i></center>';
        if (myA[0]!=0  ) {
            t.fetchOtherAllianceInfo ( t.curPage, t.eventGotOtherAlliancePage);
        }
        else {
            t.fetchOtherAllianceInfo ( t.curPage, t.eventGotOtherAlliancePage);
        }

    },


    eventGotMemberList : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            ById('allListOut').innerHTML = rslt.errorMsg;
            return;
        }
        t.memberListRslt = rslt;
        var uList = [];
        for (k in rslt.results)
            uList.push (rslt.results[k].userId);
        t.fetchPlayerStatus (uList, function(r){t.eventGotMemberOnlineList(r)});
    },

    eventGotMemberOnlineList : function (rslt){
        var t = Tabs.AllianceList;
        var numInvalid = 0;
        var numPlayers = 0;
        var myA = getMyAlliance ();
        t.dat = [];
        for (var i=0; i<t.memberListRslt.results.length; i++){
            p = t.memberListRslt.results[i];
            if (p.userId == 0){
                ++numInvalid;
            } else {
                ++numPlayers;
                if ( myA[0] == p.allianceId)
                    t.friendEta = true;
                else
                    t.friendEta = false;
                for (var c=0; c<p.cities.length; c++){
                     t.dat.push ([p.displayName, parseInt(p.might),  p.officerType, parseInt(p.numCities), parseInt(p.cities[c].tileLevel),
                         parseInt(p.cities[c].xCoord),  parseInt(p.cities[c].yCoord), p.cities[c].cityName, 0, c, p.userId,  p.avatarId, p.playerSex, p.rank, rslt.data[p.userId]?1:0,  ''+culang.shortNotAvailable+'']);
                }
            }
        }
        t.setDistances (Cities.cities[0].x, Cities.cities[0].y);
        t.ModelCity=Cities.cities[0];
        t.setEta();
        t.displayMembers (t.memberListRslt.allianceName, numPlayers);
    },
    reDisp : function (){
        var t = Tabs.AllianceList;
        function sortFunc (a, b){
            var t = Tabs.AllianceList;
            if (typeof(a[t.sortColNum]) == 'number'){
                if (t.sortDir > 0)
                    return a[t.sortColNum] - b[t.sortColNum];
                else
                    return b[t.sortColNum] - a[t.sortColNum];
            } else if (typeof(a[t.sortColNum]) == 'boolean'){

                return 0;
            } else {
                if (t.sortDir > 0)
                    return a[t.sortColNum].localeCompare(b[t.sortColNum]);
                else
                    return b[t.sortColNum].localeCompare(a[t.sortColNum]);
            }
        }
        t.dat.sort (sortFunc);
        var m = '';
        var tbody = ById('allBody');
        tbody.innerHTML ='';
        tbody.style.maxHeight = '';
        var csvXL="";
        for (var i=0; i<t.dat.length; i++){
            if (i % 2 == 0) {
                tabclass = 'xxtab';
            } else {
                tabclass = 'xxtab';
            }
             m += '<TR><TD  class='+ tabclass +'  align=left><a onclick=BoPTDme("' +  t.dat[i][0] +'");><img  src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/avatars/25/'+t.dat[i][12]+''+t.dat[i][11]+'.jpg"  align=absmiddle></a>&nbsp;<a  onclick=getInfoForAnUser("'+ t.dat[i][10] +'");>'+ t.dat[i][0]  +'</a></td><TD align=right class='+ tabclass +'>'+  addCommasInt(t.dat[i][1]) +'</td><TD align=center class='+  tabclass +'>'+ t.dat[i][3] +'</td>\
                     <TD class='+ tabclass +' align=left><span title="Spieler Rang:  '+t.dat[i][13]+'">'+ officerId2String(t.dat[i][2])   +'</span></td><TD class='+ tabclass +' align=left>'+  (t.dat[i][14]?'<SPAN  class=boldDarkRed>'+culang.mainOnline+'</span>':'')  +'</td><TD class='+ tabclass +' align=left><span  title="'+ t.dat[i][7]+'">'+ t.dat[i][7].substring(0,8)  +'</span></td><TD align=right class='+ tabclass +'>'+  t.dat[i][4] +'</td>\
                    <TD align=left class='+ tabclass +'>\
                     <a href="javascript:void(0)"  onclick="cm.utils.CoordinateLinkController.onClick(event)"  class="coordinateLink">('+ t.dat[i][5] +','+ t.dat[i][6]  +')</a>\
                    </td><TD align=left  class=xxtab style="padding-right:20px;">'+ t.dat[i][8].toFixed(2)  +'</td>';
            m += '<TD nowrap class=xxtab  align=left>'+ (t.dat[i][15]?'<SPAN>'+  (t.dat[i][15]>0?timestr(t.dat[i][15],1):''+culang.shortNotAvailable+'')   +'</span>':'<SPAN>'+culang.shortNotAvailable+'</span>')  +'</td><td class='+ tabclass +' align=left><SPAN  onclick="BoPCplo(this, \''+ t.dat[i][10]  +'\');"><A>?</a></span><td></tr>';
             csvXL +=  t.dat[i][0]+';'+t.dat[i][1]+';'+t.dat[i][5]+';'+t.dat[i][6]+';'+t.dat[i][4]+';'+t.dat[i][8]+';'+t.dat[i][7]+'\n';
        }
         m += '<tr><td  colspan=11><br><b><u>'+culang.playerExportXLS+'</u></b><BR><sup><span  class="boldRed">'+culang.mainImportant+'</span>:</sup>  <span  class="helpText">'+culang.playerExportXLSNote+'</span><BR><sup>'+culang.playerExportXLSHelp+'</sup><BR><textarea  cols="55" rows="12" onclick="this.focus();this.select();"  id="cutAndPaste"  name="csv">'+culang.mainPlayer+';'+uW.g_js_strings.commonstr.might+';X;Y;'+uW.g_js_strings.commonstr.level+';'+culang.mainDistance+';'+culang.mainCity+'\n'+csvXL+'</textarea></tr>';

        var tbody = ById('allBody');
        tbody.style.maxHeight = '';
        tbody.innerHTML = m;
        ById("cutAndPaste").innerHTML=csvXL;
        if (parseInt(tbody.clientHeight) > 475){
            tbody.style.height = '475px';
            tbody.style.maxHeight = '475px';
        }
        
    },
    setDistances : function (x, y){
        var t = Tabs.AllianceList;
        for (var i=0; i<t.dat.length; i++)
            t.dat[i][8] = distance (x, y, t.dat[i][5], t.dat[i][6]);
    },
    friendEta:false,
    setEta : function (){
        var t = Tabs.AllianceList;
        for (var i=0; i<t.dat.length; i++) {
            if (t.dat[i][8]) {
                if (ById('idFindETASelect').value>0) {
                    var eta = estETA(parseFloat(t.dat[i][8]), ById('idFindETASelect').value, t.ModelCity.id,4);
                    if (t.friendEta)
                        t.dat[i][15] = eta.friendETA;
                    else
                        t.dat[i][15] = eta.ETA;
                }
            }
        }
    },
    handleEtaSelect : function (){
        var t = Tabs.AllianceList;
        t.setEta();
        t.reDisp();
    },
    sortColNum : 1,
    sortDir : 1,
    displayMembers : function (allName, numPlayers){
        var t = Tabs.AllianceList;
        function alClickSort (e){
            var t = Tabs.AllianceList;
            var newColNum = e.id.substr(8);
            ById('clickCol'+t.sortColNum).className = 'clickable';
            e.className='clickable clickableSel';
            if (newColNum == t.sortColNum)
                t.sortDir *= -1;
            else
                t.sortColNum = newColNum;
            t.reDisp();
        }
        unsafeWindow.PTalClickSort = alClickSort;
         var m = '<STYLE>.clickable{background-color:#ddd; border:2px  outset; border-color:#555; padding-left:5px; padding-right:5px}\
            .clickableSel{background-color:#ffffcc;}\
            .xxtab{background-color:none; padding-left:5px; padding-right:5px;} </style>\
       <DIV class=pdxStat><TABLE id=tabAllMembers cellpadding=0   width=100%><TR font-weight:bold"><TD class=xtab>  &nbsp; '+ allName +'</td>\
        <TD class=xtab  width=80% align=center>'+culang.playerSearchHead+' <SPAN  id=distFrom>'+ Cities.cities[0].name +' ('+ Cities.cities[0].x +','+  Cities.cities[0].y +')</span></td><TD class=xtab  align=right>'+culang.mainPlayer+': '+ numPlayers  +'</td></tr></table></div>';
        m += '<div style="top:200px;left:5px;width:100%; max-height:'+(Options.HauteurBoite-220)+'px; overflow:auto;">\
      <TABLE id=tabAllMembers align=center cellpadding=0 cellspacing=0><THEAD>\
       <TR style="font-weight:bold"><TD id=clickCol0  onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainPlayer+'</div></a></td>\
         <TD id=clickCol1 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+uW.g_js_strings.commonstr.might+'</a></div></td>\
         <TD id=clickCol3 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainCities+'</a></div></td>\
         <TD id=clickCol2 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+culang.mainRank+'</a></div></td>\
         <TD id=clickCol14 onclick="PTalClickSort(this)" class=clickable  align=center><A><DIV>'+culang.mainOnline+'</a></div></td>\
         <TD id=clickCol7 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainCity+'</a></div></td>\
         <TD id=clickCol4 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.shortLevel+'</a></div></td>\
         <TD id=clickCol5 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.shortCoordinate+'</a></div></td>\
         <TD id=clickCol8 onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainDistance+  '</a></div></td>\
        <TD id=clickCol15  onclick="PTalClickSort(this)"  class=clickable><A><DIV>'+culang.mainArrival+'</a></div></td>\
         <TD  class=clickable><A><DIV>'+culang.mainLogin+'</div></a></td></tr></thead>\
      <tbody id=allBody ></tbody></table></div>\
     ';          //<DIV style="top:'+(Options.HauteurBoite-30)+'px;  left:0px; position:absolute; width:100%; border-top:1px solid;  margin-top:8px; color:#700; font-weight:bold;"></div>
        ById('allListOut').innerHTML = m;
        ById('altInput').innerHTML = '<TABLE width=100% cellpaddding=0><TR align=center>\
         <TD class=xtab>'+culang.playerSearchHead+' &nbsp; X:  <INPUT size=2 type=text id="plyrX" /> Y: <INPUT size=2  type=text id="plyrY" /> &nbsp;<span  id=dmcoords></span></td></tr></table>';
        ById('clickCol'+t.sortColNum).className = 'clickable clickableSel';
        t.reDisp();
        new CdispCityPicker ('plyrdcp', ById ('dmcoords'), true, t.eventCoords, 0).bindToXYboxes(ById('plyrX'), ById('plyrY'));
        ById('idFindETASelect').disabled = false;

    },

    eventCoords : function (city, x, y){
        var t = Tabs.AllianceList;
        var m = '';
        if (city != null)
            m = city.name +' ('+ city.x +','+ city.y +')';
        else
            m = x +','+ y;
        var distFrom = ById('distFrom');
        if (distFrom)
            distFrom.innerHTML = m;
        t.ModelCity=city;
        t.setDistances(x,y);
        t.setEta(x,y);
        t.reDisp();
    },

    eventGetMembers : function (aid){
        var t = Tabs.AllianceList;
         ById('allListOut').innerHTML =  '<BR><BR><CENTER><i><b>'+culang.playerPlayerDisplay+'</i></b></center>';
        t.fetchAllianceMemberList (aid, null, t.eventGotMemberList);
    },

    fetchAllianceMemberList : function (allianceId, allianceName, notify) {
        var t = Tabs.AllianceList;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.perPage = 100;
    params.type = 'might';
    params.page = 1;
        if (allianceName)
            params.allianceName = allianceName;
        if (allianceId && allianceId != 0)
            params.allianceId = allianceId;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify (rslt);
            },
        });
    },


    fetchLeaderboard : function (uid, notify) {
        var t = Tabs.AllianceList;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.userId = uid;
    params.type = 'might';
    params.page = 1;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify (rslt);
            },
        });
    },

    fetchAllianceList : function (allianceName, myAid, notify) {
        var t = Tabs.AllianceList;
        function combineResults (rsltA, rsltM, notify){
            if (!rsltA.ok){
                if (rsltA.msg.indexOf("No alliance found under")!=0 || !rsltM.ok){
                    notify (rsltA);
                    return;
                }
                rsltA.ok = true;
                rsltA.count = 0;
                rsltA.alliancesMatched = {};
            }
            if (rsltM.ok){
                 rsltA.alliancesMatched['a'+rsltM.allianceInfo.allianceId] =  {allianceId: rsltM.allianceInfo.allianceId, allianceName:  rsltM.allianceInfo.allianceName,
                    membersCount:  rsltM.allianceInfo.members, relation: null, might:  rsltM.allianceInfo.might, ranking: rsltM.allianceInfo.ranking};
                ++rsltA.count;
            }
            notify (rsltA);
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.allianceName = allianceName;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetSearchResults.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (myAid!=null && myAid>0)
                    t.fetchMyAllianceInfo  (function (r){ combineResults (rslt, r, notify)});
                else
                    notify (rslt);
            },
            onFailure: function (rslt) {
                notify (rslt);
            },
        });
    },
    fetchOtherAllianceInfo : function (pageNum, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pageNo = pageNum;
        params.cityId = unsafeWindow.currentcityid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetOtherInfo.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },

    fetchMyAllianceInfo : function (notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetInfo.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },

    fetchPlayerList : function (name, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.searchName = name;
        params.subType = "ALLIANCE_INVITE";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/searchPlayers.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },

    fetchPlayerInfo : function (uid, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.uid = uid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserGeneralInfo.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },


    fetchPlayerLastLogin : function (uid, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pid = uid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },
    fetchPlayerStatusSimple : function (uid, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.checkArr = uid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onSuccess: function (rslt) {
                notify (rslt);
            },
        });
    },

    fetchPlayerStatus : function (uidArray, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.checkArr = uidArray.join(',');
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errorMsg:'AJAX error'});
            },
        });
    },

    ModelCity : {},

};
/************************************************************************************
*                        KOC POWER - TABS2 TOURNAMENT                                *
************************************************************************************/
Tabs2.Tournament = {
    tabLabel : TabOptions.to2Tournament,
    cont:null,
    state:0,

    displayTimer : null,
    init : function (){
        this.cont = document.createElement('div');
        return this.cont;
    },
    hide : function (){
        var t = Tabs2.Tournament;
        clearTimeout (t.displayTimer);
    },
    getContent : function (){
        var t = Tabs2.Tournament;
        return t.cont;
    },
    show : function () {
        var t = Tabs2.Tournament;
        clearTimeout (t.displayTimer);
         t.cont.innerHTML = "<div  class='tourny_modal_upsell'></div><DIV  class=pdxStat>"+culang.tournamntHeadStats+" - <input type=button  value='?' id='boaidetournoi' class=buttonHelp  onclick=window.open('"+homePage+" ');></b></div>";

        //tabellenkopf
         var mhtl = "<table width=100% class=pdxTab cellspacing=0  cellpadding=0><tr><td></td><td></td>";
        for(var i=0; i<Cities.numCities; i++) {
             mhtl += "<TD align=center valign=bottom  width=60px><B>" + Cities.cities[i].name.replace(/ /g,  "<BR>") + "</B></TD>";
        }
        mhtl += "<td align=right><b>"+culang.mainTotal+"</b></td></tr>";

        //bev/h
         mhtl += "<tr><td><img height=18  src='"+IMGturnamentPop+"' title='"+culang.mainPopulation+"'>  "+culang.overviewSPop+"/h</td><td></td>";
        var pop=[],tot1=0;
        for(var i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            pop[i] =  parseInt(Seed.citystats[cityID]["pop"][1]) / 2;
            mhtl += "<td  align=right>" + addCommas(parseInt(pop[i])) +"</td>";
            tot1+=parseInt(pop[i]);
        }
        mhtl += "<td align=right><b>"+addCommas(tot1)+"</td></tr>";
        
        //truppendaten
        for(var u = 1; u < 13; u++) {
            var cost = uW.unitcost['unt' + u];
            var bev = parseInt(cost[6]);
            var might = parseInt(uW.unitmight['unt' + u]);
            mhtl +="<tr><td style='border-top:1px solid black;'>"+cost[0]+"/h</td>";
             mhtl +="<td style='border-top:1px solid  black;'>"+culang.tmax+"<br>"+culang.treal+"<br>"+culang.tmight+"</td>";
            var Gmax = 0;
            var Greal = 0;
            var Gmacht = 0;
            for(var i=0; i<Cities.numCities; i++) {
                var city = getTroopDefTrainEstimates(Cities.cities[i].id);
                var max = ((city['Troop'+u+'Time'] > 0)?(36000000 / city['Troop'+u+'Time']):0);
                var real = parseInt(pop[i]/bev);
                if (real < max) {
                    var color = "green";
                } else {
                    real = max;
                    var color = "red";
                }
                var macht = real * might;
                mhtl += "<td  style='border-top:1px solid black;' align=right>";
                mhtl += addCommas(parseInt(max)) + '<br>';
                mhtl += '<span style="color:'+color+';">' + addCommas(parseInt(real)) + '</span><br>';
                mhtl += '<span style="color:blue;">' + addCommas(parseInt(macht)) + '</span>';
                mhtl += "</td>";
                Gmax += max;
                Greal+= real;
                Gmacht+= macht;
            }
            if (Greal < Gmax) {
                    var color = "green";
                    
                } else {
                    real = max;
                    var color = "red";
                }
            mhtl += "<td  style='border-top:1px solid black;' align=right>";
            mhtl += "<b>"+addCommas(parseInt(Gmax))+"<br>";
            mhtl += '<span style="color:'+color+';">' + addCommas(parseInt(Greal))+"</span><br>";
            mhtl += '<span style="color:blue;">' + addCommas(parseInt(Gmacht)) + '</span></b>';
            mhtl += "</td></tr>";
        }
    
        //Moral
         mhtl  +="<tr><td>&nbsp;</td></tr><tr><td><img  height=20 src='"+IMGhappiness+"'  title='"+culang.mainLuck+"'></td><td></td>";
        for(var i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            var bon = parseInt(Seed.citystats[cityID]["pop"][2]);
            var bonc = "red";
            if (bon>99) bonc="green";
            mhtl += "<td align=right style='color:"+bonc+"'><b>"+bon+"</td>";
        }
        
        //Ausbildungswarteschlange
        var now = unixTime();
        var totalpop=0;
         mhtl += "</tr><tr><td  title='"+culang.tournamntTitleTrainTime+"'>"+culang.tournamntTrainTime+"</td><td></td>";
        var phtl = "</tr><tr><td>"+culang.tournamntPopInTrain+"</td><td></td>";
        for(var i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            var totTime = 0;
            var q = Seed.queue_unt[cityID];
            if (q!=null && q.length>0) {
                totTime = q[q.length-1][3] - now;
                totalpop=0;
                for (var zz=0; zz<q.length; zz++){
                    //totalpop += parseInt((parseInt(q[zz][1]) * unsafeWindow.unitcost['unt'+q[zz][0]][6]) / 2);
                    totalpop += parseInt(q[zz][1]);
                }
            }
            if (totTime < 0) totTime = 0;
            if (totTime < 3600)
                var bonc="style='color:red'";
            else
                var bonc="";
            mhtl += "<td align=right "+bonc+"><b>"+timestr(totTime)+"</td>";
            phtl += "<td align=right "+bonc+"><b>"+addCommas(totalpop)+"</td>";
        }
        //Erz
         mhtl +=  '<tr><td></td></tr>'+phtl+'<tr><td><img  height=18 src="'+IMGiron30+'"></td><td></td>'
        for(var i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            var mine=Seed.resources[cityID]['rec4'][0] / 3600
            var bonc="";
            if (mine<=15000000)
                var bonc="style='color:red'";

            mhtl += '<td "+bonc+" align=right><b>'+UniteKMG(parseInt(mine)) +'</td>';
        }
        mhtl += "</tr></table>";

        mhtl += "<DIV class=pdxStat>"+culang.tournamenCheckHead+"</div>";
        t.cont.innerHTML += mhtl;
        //Turnierdaten 
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.format=2;
        params.tournyPos=0;
         new  AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/getLeaderboard.php"+unsafeWindow.g_ajaxsuffix,  {  method:"post",  parameters:params,
            onSuccess:function(transport){
                var rslt=eval("("+transport.responseText+")");
                if(rslt.ok){
                    if(!rslt.data){
                         t.cont.innerHTML +="<div  class='tourny_modal_upsell'><br><center><b>"+unsafeWindow.g_js_strings.modal_tourny_changetab.notourny+"</b></center></div><br>";
                    }else{ // fin rslt.data
                        var tournyhtml=new Array();
                        if(rslt.name){
                             tournyhtml.push(" <div   style='font-variant: small-caps; font-size:20px; text-align:  center;'><b><i>"+culang.tournamntOfMight+"</i></b></div>")
                             //  tournyhtml.push("<div><center><b>"+rslt.name.replace('The  Tournament of  Might',''+culang.tournamntOfMight+'')+"</u></b></center></div>")
                        }  else{
                             tournyhtml.push("<div  class='tournymodaltitle'><center><b><i>"+unsafeWindow.g_js_strings.commonstr.tournament+"</i></b></div>")
                        }
                        tournyhtml.push("<div>");
                        if(rslt.startdate&&rslt.enddate){
                            var startTime=rslt.startdate;
                            var endTime=rslt.enddate;
                            var now=parseInt(new Date().getTime()/1000);
                             tournyhtml.push("<table width=100%  align=center class=pdxTab><tr><td width=40%><span  class='boldGreen'><u>"+culang.tournamntStart+"</u></span></td><td  width=40%><span  class='boldRed'><u>"+culang.tournamntEnd+"</u></span></td><td  width=20%><span  class='boldRed'><u>"+culang.tournamntRemain+"</u></span></td></tr>");
                            dt = new Date ();
                            dt.setTime (startTime * 1000);
                            dtf = new Date ();
                            dtf.setTime (endTime * 1000);
                            var restant = endTime - now;
                            tournyhtml.push("<tr><td>");
                            tournyhtml.push("" + dt.toLocaleDateString() + " - "+ dt.toLocaleTimeString());
                            tournyhtml.push("</td><td>");
                            tournyhtml.push("" + dtf.toLocaleDateString()+ " - "+ dtf.toLocaleTimeString());
                            tournyhtml.push("</td><td>"+timestr(restant,1)+"</td></tr></table>");
                            tournyhtml.push("<br>");
                        }
                         tournyhtml.push("<center><DIV  style='max-height:400px; overflow-y:auto;'><select  id='resizeTournamentList'><option  value=5>5</option><option  value=10>10</option><option  value=25>25</option><option  value=50>50</option><option  value=100>100</option></select><table  class='tournamentTable' cellpadding='0' cellspacing='0' border='0'  width=95% style='margin:3px'>");
                        tournyhtml.push("<thead>");
                        tournyhtml.push("<tr>");
                        if(rslt.type==24){
                            tournyhtml.push("<td class='rankcol'>");
                             tournyhtml.push("<div  ><b><u>"+culang.tournamntPlace+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td>");
                             tournyhtml.push("<div  ><b><u>"+unsafeWindow.g_js_strings.modal_tourny_changetab.chancellorname+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td>");
                              tournyhtml.push("<div><b><u>"+unsafeWindow.g_js_strings.commonstr.alliance+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td>");
                             tournyhtml.push("<div  ><b><u>"+unsafeWindow.g_js_strings.modal_tourny_changetab.mightgained+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td > ");
                             tournyhtml.push("<div  ><b><u>"+unsafeWindow.g_js_strings.modal_tourny_changetab.rewardperplayer+"</u></b></div>");
                            tournyhtml.push("</td>")
                        }else{
                            tournyhtml.push("<td class='rankcol' >");
                              tournyhtml.push("<div><b><u>"+culang.tournamntPlace+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td>");
                              tournyhtml.push("<div><b><u>"+culang.mainPlayer+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td >");
                             tournyhtml.push("<div  ><b><u>"+unsafeWindow.g_js_strings.commonstr.alliance+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td >");
                             tournyhtml.push("<div  ><b><u>"+uW.g_js_strings.commonstr.might+"</u></b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td>");
                             tournyhtml.push("<div  ><b><u>"+culang.tournamentReward+"</u></b></div>");
                            tournyhtml.push("</td>")
                        }
                        tournyhtml.push("</tr>");
                        tournyhtml.push("</thead>");
                        tournyhtml.push("</tbody>");
                        var nb=rslt.data.length;
                        var votrepuissance = 0;
                        for(var i=0;i<rslt.data.length;i++){
                            var row=rslt.data[i];
                            if(rslt.type==24){
                                // pour le tournoi alliance
                                if (getMyAlliance()[1] == row.alliance) {
                                    votrepuissance=row.contestValue;
                                    break;
                                }
                            } else {
                                if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
                                    votrepuissance=row.contestValue;
                                    break;
                                }
                            }
                        }
                        for(var i=0;i< Options.TournoiLigne;i++){
                            var row=rslt.data[i];
                            var rewardString=row.itemCount+" ";
                            if(row.itemType==0){
                                rewardString+=unsafeWindow.g_js_strings.commonstr.gems;
                            }else{
                                rewardString+=unsafeWindow.itemlist["i"+row.itemType].name;
                            }
                            var couleur="";
                            if(rslt.type==24){
                                // pour le tournoi alliance
                                if (getMyAlliance()[1] == row.alliance) {
                                    couleur=" style='background-color:#77FF77' ";
                                }
                            }else{
                                if (getMyAlliance()[1] == row.alliance) {
                                    if(i%2==1){
                                        couleur=" style='background-color:#FF9977' ";
                                    }else{
                                        couleur=" style='background-color:#FFAA88' ";
                                    }
                                }
                                if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
                                    couleur=" style='background-color:#77FF77' ";
                                }
                            }
                            if(i%2==1){
                                tournyhtml.push("<tr>")
                            }else{
                                tournyhtml.push("<tr class='stripe'>")
                            }
                            tournyhtml.push("<td class='rankcol' "+couleur+">");
                            tournyhtml.push("<div><b>"+row.ranking+"</b></div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td "+couleur+">");
                            tournyhtml.push("<div>"+row.name+"</div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td "+couleur+">");
                            tournyhtml.push("<div>"+(row.alliance||"----")+"</div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td "+couleur+">");
                            tournyhtml.push("<div>"+addCommas(row.contestValue));
                            if (votrepuissance>0) {
                                var ecartavecvous = parseInt(row.contestValue - votrepuissance);
                                if (ecartavecvous>0) {
                                    tournyhtml.push("&nbsp;(+ " + addCommas(ecartavecvous) +")");
                                }
                                if (ecartavecvous<0) {
                                    tournyhtml.push("&nbsp;(" + addCommas(ecartavecvous) +")");
                                }
                            }
                            tournyhtml.push("</div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("<td "+couleur+">");
                            tournyhtml.push("<div>"+rewardString+"</div>");
                            tournyhtml.push("</td>");
                            tournyhtml.push("</tr>")
                        } // fin du for
                        if(rslt.type!=24){
                            for(var i= Options.TournoiLigne;i<rslt.data.length;i++){
                                var row=rslt.data[i];
                                if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
                                    var rewardString=row.itemCount+" ";
                                    if(row.itemType==0){
                                        rewardString+=unsafeWindow.g_js_strings.commonstr.gems;
                                    }else{
                                        rewardString+=unsafeWindow.itemlist["i"+row.itemType].name;
                                    }
                                    tournyhtml.push("<tr class='stripe' >")
                                    tournyhtml.push("<td class='rankcol' style='background-color:#77FF77'>");
                                    tournyhtml.push("<div><b>"+row.ranking+"</b></div>");
                                    tournyhtml.push("</td>");
                                    tournyhtml.push("<td style='background-color:#77FF77'>");
                                    tournyhtml.push("<div>"+row.name+"</div>");
                                    tournyhtml.push("</td>");
                                    tournyhtml.push("<td style='background-color:#77FF77'>");
                                    tournyhtml.push("<div>"+(row.alliance||"----")+"</div>");
                                    tournyhtml.push("</td>");
                                    tournyhtml.push("<td style='background-color:#77FF77'>");
                                    tournyhtml.push("<div>"+addCommas(row.contestValue)+"</div>");
                                    tournyhtml.push("</td>");
                                    tournyhtml.push("<td style='background-color:#77FF77'>");
                                    tournyhtml    .push("<div>"+rewardString+"</div>");
                                    tournyhtml.push("</td>");
                                    tournyhtml.push("</tr>")
                                }
                            }
                        }
                        tournyhtml.push("</tbody>");
                        tournyhtml.push("</table>");
                        tournyhtml.push("</div></div>");
                        t.cont.innerHTML += tournyhtml.join("");

                        ById('resizeTournamentList').addEventListener ('change',
                            function() {
                                Options.TournoiLigne=ById('resizeTournamentList').value;
                                saveOptions();
                                t.show();
                            }, false);

                        ById('resizeTournamentList').value=Options.TournoiLigne;

                    } // fin rslt.data 
                } else {
                     t.cont.innerHTML = "<div  class='tourny_modal_upsell'><center>"+culang.tournamntErrorLoading+"</div>";
                }
            }, onFailure:function()  {
                 t.cont.innerHTML = "<div  class='tourny_modal_upsell'><center>"+culang.tournamntErrorLoading+"</div>";
            }
        });
        t.displayTimer = setTimeout (t.show, 240000);
    },

},
/************************************************************************************
 *                        KOC POWER - TABS2 PRODUCTION                                *
 ************************************************************************************/
Tabs2.Overview = { //TODO rename to Overview2
    cont : null,
    displayTimer : null,
    checkBox:null,
    checkBox1:null,
    Overview : function (){
    },
    init : function (){
        this.cont = document.createElement('div');
        return this.cont;
    },
    getContent : function (){
        return Tabs2.Overview.cont;
    },
    hide : function (){
        clearTimeout (Tabs2.Overview.displayTimer);
    },
    show : function (){
        var rownum = 0;
        var totalentre = 0;
        var t = Tabs2.Overview;
        clearTimeout (t.displayTimer);
        function _row (name, row, noTotal, typee){
            if (rownum++ % 2)
                style = '';
            else
                style = ' style = "background: #e8e8e8"';
            var tot = 0;
            var m = [];
            m.push ('<TR style="background: #fff" align=right');
            m.push (style);
            m.push ('><TD');
            m.push (style);
            m.push ('><B>');
            m.push (name);
            m.push ('</td>');
            if (noTotal){
                m.push ('<TD');
                m.push (style);
                m.push ('>&nbsp;</td>');
            } else {
                for (i=0; i<row.length; i++)
                    tot += row[i];
                m.push ('<TD style="background: #ffc">');
                if (tot<0) {
                    m.push ("<SPAN class=class=boldRed>"+addCommas(tot)+"</span>");
                } else {
                    m.push (addCommas(tot));
                }
                m.push ('</td>');
            }
            for (i=0; i<row.length; i++){
                m.push ('<TD');
                m.push (style);
                m.push ('>');
                m.push (addCommas(row[i]));
                m.push ('</td>');
            }
            m.push ('</tr>');
            return m.join('');
        }
        try {
            if (Options.includeMarching)
                march = getMarchInfo ();
            dt = new Date ();
            dt.setTime (Seed.player.datejoinUnixTime * 1000);
            var now = unixTime();
             str = "<DIV  class=pdxStat>"+culang.ressourceProduction+"</div><TABLE  class=pdxTabLined cellspacing=0><TR valign=top  align=right><TD width=65></td><TD width=88  style='background:  #ffc'><B>"+culang.mainHTotal+"</b></td>";
            for(i=0; i<Cities.numCities; i++) {
                str += "<TD width=81><B>"+ Cities.cities[i].name.substring(0,10) +'</b></td>';
            }
            if (Options.includeMarching)
                str += '<TD width=81><B>'+uW.g_js_strings.commonstr.marching+'</b></td>';
            str += "<td></td></tr>";
            rows = [];
            rows[0] = [];
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
            }
            for (r=1; r<6; r++){
                rows[r] = [];
                for(i=0; i<Cities.numCities; i++) {
                    cityID = 'city'+ Cities.cities[i].id;
                    if (r==5)
                        rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
                    else
                        rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
                }
            }
            if (Options.includeMarching){
                for (var i=0; i<6; i++)
                    // rows[i][Cities.numCities] = march.resources[i];
                    rows[i][Cities.numCities] = parseIntNan(march.resources[i]);
            }
             str += _row ('<img  title="'+unsafeWindow.g_js_strings.commonstr.gold+'" height=18  src="'+IMGgold30+'">', rows[0], false, 0);
            str += _row  ('<img title="'+unsafeWindow.g_js_strings.commonstr.food+'"  height=18 src="'+IMGfood30+'">', rows[1], false, 0);
             str += _row ('<img  title="'+unsafeWindow.g_js_strings.commonstr.wood+'" height=18  src="'+IMGwood30+'">', rows[2], false, 0);
            str += _row  ('<img title="'+unsafeWindow.g_js_strings.commonstr.stone+'"  height=18 src="'+IMGstone30+'">', rows[3], false, 0);
             str += _row ('<img  title="'+unsafeWindow.g_js_strings.commonstr.ore+'" height=18  src="'+IMGiron30+'">', rows[4], false, 0);
            str += _row  ('<img title="'+unsafeWindow.g_js_strings.commonstr.aetherstone+'"  height=18 src="'+IMGastone30+'">', rows[5], false, 0);
            str += '<TR><TD><BR></td></tr>';
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                row[i] = rp[1];
            }
            str += _row ('<img height=18 title="'+culang.overviewFoodProduce+'" src="'+IMGfood30+'">', row, false, 0);
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                row[i] = rp[2];
            }
            str += _row ('<img height=18 title="'+culang.overviewWoodProduce+'" src="'+IMGwood30+'">', row, false, 0);
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                row[i] = rp[3];
            }
            str += _row ('<img height=18 title="'+culang.overviewStoneProduce+'" src="'+IMGstone30+'">', row, false, 0);
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                row[i] = rp[4];
            }
            str += _row ('<img height=18 title="'+culang.overviewIronProduce+'" src="'+IMGiron30+'">', row, false, 0);
            str += '<TR><TD><font size=1><BR></td></tr>';
            row = [];
            var totalbouffe = 0;
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                var usage = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
                row[i] = rp[1] - usage;
            }
            str += _row (''+culang.overviewSProduce+'', row, false,  0);
            for(i=0; i<Cities.numCities; i++) {
                if (row[i] >= 0)
                    row[i] = '----';
                else {
                    var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                    if (timeLeft > 86313600)
                        row[i] = '----';
                    else {
                        if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                            row[i] = '<SPAN class=whiteOnRed>'+ timestrShort(timeLeft) +'</span>';
                        else
                            row[i] = timestrShort(timeLeft);
                    }
                }
            }
            str += _row (''+culang.overviewFoodLeft+'', row, true, 0);
            str += '<TR><TD><font size=1><BR></td></tr>';
            for (r=1; r<14; r++){
                rows[r] = [];
                for(i=0; i<Cities.numCities; i++) {
                    cityID = 'city'+ Cities.cities[i].id;
                    rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
                }
            }
            if (Options.includeMarching){
                for (var i=0; i<14; i++)
                    rows[i][Cities.numCities] = march.marchUnits[i];
            }
            str += "</table>";
            Tabs2.Overview.cont.innerHTML = str;
        } catch (e){
            Tabs2.Overview.cont.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';
        }
        t.displayTimer = setTimeout (t.show, 5000);
    },
};
/************************************************************************************
 *                        KOC POWER - TABS2 COMBAT                                    *
 ************************************************************************************/
Tabs2.Combat = {
    cont: null,
    troops: [{},{}], //Array[Defender, Attacker]
    active: [{},{}],
    lost: [{},{}],
    total: [],
    stats: unsafeWindow.unitstats,   //  Life, Attack, Defense, Speed, Range, Load
    priority: [[3,7,8,4,5,6,2,1,9,11,10,12],[12,10,6,3,7,8,4,5,2,1,9,11]],
    round: 0,
    range: [0,0,0], //[Defender, Attacker, Max]
    distance: [{},{}], // [Defender, Attacker]
    speed: [0,0], // [Defender max, Attacker max]
    start: 0,
    pop:null,
    getContent : function (){
        var t = Tabs2.Combat;
        return t.cont;
    },
    init: function(div){
        var t = Tabs2.Combat;
        t.cont = document.createElement('div');
        return t.cont;
    },
    show: function() {
        var t = Tabs2.Combat;
         var m = '<div  class=pdxStat>'+culang.combatHead+'</div><sup><span  class="boldRed">'+culang.mainImportant+'</span>:</sup>  <span  class="helpText">'+culang.combatNote+'</span><table><TR><TD   colspan=2><b><u>'+culang.mainAttacker+'</u></b>:  <INPUT id=pbcombat_1 type=submit  value="'+uW.g_js_strings.commonstr.research+'"></b></td><TD   colspan=2><b><u>'+culang.mainDefender+'</u></b>:  <INPUT id=pbcombat_0 type=submit  value="'+uW.g_js_strings.commonstr.research+'"></b></td></TR>';
        for(var troops in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[troops][0];
             m+='<tr><td>'+name+':  </td><td><input type=text id="pbcombata_'+troops+'"  /></td><td>'+name+': </td><td><input  type=text id="pbcombatd_'+troops+'" /></td></tr>';
        }
        m+='</table><DIV id=pbcombat_rslt></div>';
        t.cont.innerHTML = m;

        for(var troops in unsafeWindow.unitcost){
            ById('pbcombata_'+troops).addEventListener('change', t.e_calculate, false);
            ById('pbcombatd_'+troops).addEventListener('change', t.e_calculate, false);
        }
        ById('pbcombat_0').addEventListener('click', function() t.e_research(0),false);
        ById('pbcombat_1').addEventListener('click', function() t.e_research(1),false);
    },
    e_research : function(side){
        var t = Tabs2.Combat;
        t.pop = new CPopup ('pbcombatresearch', 0, 0, 270, 300, true, function(){t.c_ratio(); t.pop.destroy();});
        t.pop.centerMe (mainPop2.getMainDiv());
         t.pop.getTopDiv().innerHTML = '<div  class="popupBanner">'+culang.combatResearchHead+'  </div><center><b><i>'+  (side?''+culang.mainAttacker+'':''+culang.mainDefender+'')  +'</i></b></center>';
        var m = '<DIV><TABLE>';
        for(var k in CombatOptions.research[side]){
             m +=  '<TR><TD>'+unsafeWindow.techcost[k][0]+':</td><td><input  id="pbcombat_'+k+'" /></td></tr>';
        }
         m += '<TR><TD>'+culang.mainKnights+':  </td><td><input id="pbcombat_knt" value='+  CombatOptions.knt[side] +' /></td></tr>';
        m += '<TR><TD>'+culang.mainGuardian+': </td><td> \
               <table><tr><td>'+culang.mainType+':  </td><td>'+  htmlSelector({wood:''+uW.g_js_strings.commonstr.wood+'',ore:''+uW.g_js_strings.commonstr.ore+''},CombatOptions.guardian[side][0],'id=pbcombat_guartype')  +'</td></tr><tr>\
               <td>'+uW.g_js_strings.commonstr.level+':  </td><td><input id="pbcombat_guarlvl" value='+  CombatOptions.guardian[side][1] +' size=4  /></td></tr></table>\
              </td></tr>';
        m += '<TR><TD colspan=2><CENter>';
        if (side==1) {
            m+='<button id=pbcombatmyresearch>'+culang.combatMyResearch+'</button>'
        }
         m+='<button  id=pbcombatresearchsave>'+culang.buttonSave+'</button></CENTER></td></tr></table></div>';
        t.pop.getMainDiv().innerHTML = m;
        t.pop.centerMe (mainPop2.getMainDiv());
        t.pop.show (true);
        for(var k in CombatOptions.research[side]){
            t.e_saveresearch('pbcombat_'+k, k, side);
        }
        ById('pbcombat_knt').addEventListener('change',function(){
            CombatOptions.knt[side] = parseInt(ById('pbcombat_knt').value);
            saveCombatOptions();
        },false);
        ById('pbcombat_guartype').addEventListener('change',function(){
            CombatOptions.guardian[side][0] = ById('pbcombat_guartype').value;
            saveCombatOptions();
        },false);
        ById('pbcombat_guarlvl').addEventListener('change',function(){
            CombatOptions.guardian[side][1] = parseInt(ById('pbcombat_guarlvl').value);
            saveCombatOptions();
        },false);
        ById('pbcombatresearchsave').addEventListener('click',t.c_ratio,false);

        ById('pbcombatresearchsave').addEventListener('click',t.c_ratio,false);
        if (side==1) {

            ById('pbcombatmyresearch').addEventListener('click', function () {

                getResearchLevels ();
                CombatOptions.research[1]['tch8']=researchLevels[8].Level;
                CombatOptions.research[1]['tch9']=researchLevels[9].Level;
                CombatOptions.research[1]['tch13']=researchLevels[13].Level;
                CombatOptions.research[1]['tch15']=researchLevels[15].Level;

                var marshallCombatScore = 0;
                if (parseIntNan(Options.alertConfig.hq)>0) {
                    var s = Seed.knights['city'+Options.alertConfig.hq];
                    if (s) {
                        s = s["knt" + Seed.leaders['city'+Options.alertConfig.hq].combatKnightId];
                        if (s){
                            marshallCombatScore = s.combat;
                        }
                    }
                }
                CombatOptions.knt[1] = marshallCombatScore;

                for(var i=0; i < Cities.numCities; i++){
                    if(Seed.guardian[i].cityId == Options.alertConfig.hq){
                        CombatOptions.guardian[1][1]= Seed.guardian[i].level;
                        CombatOptions.guardian[1][0]= Seed.guardian[i].type;
                    }
                }

                saveCombatOptions();
                t.e_research(1);

            },false);


        }
    },

    e_saveresearch : function(checkboxId, optionName, side){
        var t = Tabs2.Combat;
        var checkbox = ById(checkboxId);
        if (CombatOptions.research[side][optionName])
            checkbox.value = CombatOptions.research[side][optionName];
        checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, side).handler, false);
        function eventToggle (checkboxId, optionName, side){
            this.handler = handler;
            var optName = optionName;
            function handler(event){
                CombatOptions.research[side][optionName] = parseInt(this.value);
                saveCombatOptions();
            }
        }
    },

    c_ratio : function (){
        var t = Tabs2.Combat;
        for(var k in CombatOptions.ratio[0]){
            var attack = parseFloat(t.c_attack(k,0));
            for(var tr in unsafeWindow.unitcost){
                var defense = parseFloat(t.c_defense(tr,1));
                var life = parseFloat(t.c_life(tr,1));
                var ratio = ((life+defense)/attack);
                CombatOptions.ratio[0][k][tr] = ratio.toFixed(20);
            }
        }
        for(var k in CombatOptions.ratio[1]){
            var attack = parseFloat(t.c_attack(k,1));
            for(var tr in unsafeWindow.unitcost){
                var defense = parseFloat(t.c_defense(tr,0));
                var life = parseFloat(t.c_life(tr,0));
                var ratio = ((life+defense)/attack);
                CombatOptions.ratio[1][k][tr] = ratio.toFixed(20);
            }
        }
    },
    e_calculate: function(){
        var t = Tabs2.Combat;
        t.round = 0;
        t.total[0] = 0;
        t.total[1] = 0;
        t.range[0] = 0
        t.range[1] = 0;
        t.speed[0] = 0;
        t.speed[1] = 0;
        for(var tr in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[tr][0];
            t.troops[0][tr] = parseIntNan(ById('pbcombatd_'+tr).value);
            t.troops[1][tr] = parseIntNan(ById('pbcombata_'+tr).value);
            t.total[0] += t.troops[0][tr];
            t.total[1] += t.troops[1][tr];
            t.lost[0][tr] = 0;
            t.lost[1][tr] = 0;
            t.active[0][tr] = 0;
            t.active[1][tr] = 0;
            if(t.troops[0][tr]>0 && parseInt(t.stats[tr][4]) > t.range[0]) t.range[0] = parseInt(t.stats[tr][4]);
            if(t.troops[1][tr]>0 && parseInt(t.stats[tr][4]) > t.range[1]) t.range[1] = parseInt(t.stats[tr][4]);
            if(t.troops[0][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[0]) t.speed[0] = parseInt(t.stats[tr][3]);
            if(t.troops[1][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[1]) t.speed[1] = parseInt(t.stats[tr][3]);
        }
        if(t.range[1]>t.range[0]){
            t.start = 1; //Attacker starts first if range is longer than defender
            t.range[2] = t.range[1];
        } else {
            t.start = 0;
            t.range[2] = t.range[0];
        }
        for(var tr in unsafeWindow.unitcost){
            if(t.troops[0][tr]>0)
                t.distance[0][tr] = parseInt(t.range[2]/((t.speed[1]/t.speed[0])+1));
            else
                t.distance[0][tr] = 0;
            if(t.troops[1][tr]>0)
                t.distance[1][tr] = parseInt(t.range[2]/((t.speed[0]/t.speed[1])+1));
            else
                t.distance[1][tr] = 0;
        }
        t.c_rounds();
    },

    c_rounds: function(){
        var t = Tabs2.Combat;
        if(t.total[0]<1 || t.total[1]<1 || t.round>99){

            t.print();
            return;
        }
        t.round++;
        if(t.round>1){
            for(var tr in t.distance[0]){
                t.distance[0][tr] -= t.stats[tr][3];
                if(t.distance[0][tr] < 1) t.distance[0][tr] = 0;
            }
            for(var tr in t.distance[1]){
                t.distance[1][tr] -= t.stats[tr][3];
                if(t.distance[1][tr] < 1) t.distance[1][tr] = 0;
            }
        }
        t.c_remainder();
    },

    c_remainder: function(){  //  Life, Attack, Defense, Speed, Range, Load
        var t = Tabs2.Combat;
        for(var tr in t.troops[0]){ //Only troops in range are counted
            if(t.stats[tr][4] >= (t.distance[0][tr]))
                t.active[0][tr] = t.troops[0][tr];
        }
        for(var tr in t.troops[1]){
            if(t.stats[tr][4] >= (t.distance[1][tr]))
                t.active[1][tr] = t.troops[1][tr];
        }
        //Defender
        for(var tr in t.active[0]){
            if(t.active[0][tr] < 1) continue;
            var range = t.stats[tr][4] - t.distance[0][tr];
            var count = 0;
            var type = 0;
            if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
            // GM_log('side0 '+type);
            while(t.active[0][tr] > 0 && count<t.priority[type].length){
                var trr = 'unt'+t.priority[type][count];
                if((t.troops[1][trr] < 1) || (range < t.distance[1][trr])){
                    count++;
                    continue;
                }
                if(parseInt(CombatOptions.ratio[0][tr][trr]) < 1){
                    if(t.active[0][tr] > t.troops[1][trr]){
                        t.active[0][tr] -= t.troops[1][trr];
                        t.lost[1][trr] += t.troops[1][trr];
                        t.total[1] -= t.troops[1][trr];
                        t.troops[1][trr] = 0;
                    }else {
                        t.lost[1][trr] += t.active[0][tr];
                        t.total[1] -= t.active[0][tr];
                        t.troops[1][trr] -= t.active[0][tr];
                        t.active[0][tr] = 0;
                    }
                } else {
                    var killed = parseInt(t.active[0][tr]/CombatOptions.ratio[0][tr][trr]);
                    if(killed > t.troops[1][trr]){
                        t.lost[1][trr] += t.troops[1][trr];
                        t.total[1] -= t.troops[1][trr];
                        t.active[0][tr] -= parseInt(CombatOptions.ratio[0][tr][trr]* t.troops[1][trr]);
                        t.troops[1][trr] = 0;
                    } else {
                        t.lost[1][trr] += killed;
                        t.total[1] -= killed;
                        t.troops[1][trr] -= killed;
                        t.active[0][tr] = 0;
                    }
                }
                count++;
            }
        }

        //Attacker
        for(var tr in t.active[1]){
            if(t.active[1][tr] < 1) continue;
            var range = t.stats[tr][4] - t.distance[1][tr];
            var count = 0;
            var type = 0;
            if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
            // GM_log('side1 '+type);
            while(t.active[1][tr] > 0 && count<t.priority[type].length){
                var trr = 'unt'+t.priority[type][count];
                if((t.troops[0][trr] < 1) || (range < t.distance[0][trr])){
                    count++;
                    continue;
                }
                if(parseInt(CombatOptions.ratio[1][tr][trr]) < 1){
                    if(t.active[1][tr] > t.troops[0][trr]){
                        t.active[1][tr] -= t.troops[0][trr];
                        t.lost[0][trr] += t.troops[0][trr];
                        t.total[0] -= t.troops[0][trr];
                        t.troops[0][trr] = 0;
                    }else {
                        t.lost[0][trr] += t.active[1][tr];
                        t.total[0] -= t.active[1][tr];
                        t.troops[0][trr] -= t.active[1][tr];
                        t.active[1][tr] = 0;
                    }
                } else {
                    var killed = parseInt(t.active[1][tr]/CombatOptions.ratio[1][tr][trr]);
                    if(killed > t.troops[0][trr]){
                        t.lost[0][trr] += t.troops[0][trr];
                        t.total[0] -= t.troops[0][trr];
                        t.active[1][tr] -= parseInt(CombatOptions.ratio[1][tr][trr]* t.troops[0][trr]);
                        t.troops[0][trr] = 0;
                    } else {
                        t.lost[0][trr] += killed;
                        t.total[0] -= killed;
                        t.troops[0][trr] -= killed;
                        t.active[1][tr] = 0;
                    }
                }
                count++;
            }
        }
        t.c_rounds();
    },
    c_attack: function(tr,side){
        var t = Tabs2.Combat;
        var att = t.stats[tr][1];
        if(CombatOptions.research[side].tch8) //Add Poison Edge
            att += t.stats[tr][1]*parseFloat(CombatOptions.research[side].tch8*5/100);
        if(CombatOptions.guardian[side][0] == 'ore' && side == 1){ //Add Guardian Boost
            var boost = 0;
            switch(CombatOptions.guardian[side][1]){
                case 1:
                    boost = 0.02;
                    break;
                case 2:
                    boost = 0.04;
                    break;
                case 3:
                    boost = 0.06;
                    break;
                case 4:
                    boost = 0.08;
                    break;
                case 5:
                    boost = 0.12;
                    break;
                case 6:
                    boost = 0.16;
                    break;
                case 7:
                    boost = 0.20;
                    break;
                case 8:
                    boost = 0.26;
                    break;
                case 9:
                    boost = 0.32;
                    break;
                case 10:
                    boost = 0.40;
                    break;
                default:
                    boost = 0;
            }
            att += t.stats[tr][1]*boost;
        }
        if(CombatOptions.knt[side]) //Add knight boost
            att += t.stats[tr][1]*parseFloat((CombatOptions.knt[side]/2)/100);
        return att;
    },
    c_defense: function(tr,side){
        var t = Tabs2.Combat;
        var def = t.stats[tr][2];
        if(CombatOptions.research[side].tch9) //Add Metal Alloy
            def += t.stats[tr][2]*parseFloat(CombatOptions.research[side].tch9*5/100);
        if(CombatOptions.knt[side]) //Add knight boost
            def += t.stats[tr][2]*parseFloat((CombatOptions.knt[side]/2)/100);
        return def;
    },
    c_life: function(tr,side){
        var t = Tabs2.Combat;
        var life = t.stats[tr][0];
        if(CombatOptions.research[side].tch15) //Add Healing Potions
            life += t.stats[tr][0]*parseFloat(CombatOptions.research[side].tch15*5/100);
        if(CombatOptions.guardian[side][0] == 'wood' && side == 0){ //Add Guardian Boost
            var boost = 0;
            switch(CombatOptions.guardian[side][1]){
                case 1:
                    boost = 0.01;
                    break;
                case 2:
                    boost = 0.02;
                    break;
                case 3:
                    boost = 0.03;
                    break;
                case 4:
                    boost = 0.04;
                    break;
                case 5:
                    boost = 0.06;
                    break;
                case 6:
                    boost = 0.08;
                    break;
                case 7:
                    boost = 0.10;
                    break;
                case 8:
                    boost = 0.13;
                    break;
                case 9:
                    boost = 0.16;
                    break;
                case 10:
                    boost = 0.20;
                    break;
                default:
                    boost = 0;
            }
            life += t.stats[tr][0]*boost;
        }

        return life;
    },
    print: function (){
        var t = Tabs2.Combat;
         var m = '<div  class=pdxStat>'+culang.combatResultHead+'</div><table  width=100%><TR><td><b><u>'+culang.mainTroops+'</u></b></td><TD   colspan=1><b><u>'+culang.mainAttacker+'</b></u></td><td><b><u>'+culang.reportKilled+'</u></b></td><TD><b><u>'+culang.mainDefender+'</u></b></td><td><b><u>'+culang.reportKilled+'</u></b></td><TD><b><u>'+culang.mainRounds+'</u></b>:  <span  class="boldRed">'+t.round+'</span></td></TR>';
        for(var tr in unsafeWindow.unitcost){
            var name = unsafeWindow.unitcost[tr][0];
             m+='<tr><td>'+name+': </td><td>'+  t.troops[1][tr]  +'</td><td>'+t.lost[1][tr]+'</td><td>'+  t.troops[0][tr]  +'</td><td>'+t.lost[0][tr]+'</td></tr>';
        }
        m+='</table>';
        ById('pbcombat_rslt').innerHTML = m;
    },
    hide: function(){},
}
/************************************************************************************
 *                        KOC POWER - TABS2 ALLIANCE                                    *
 ************************************************************************************/
Tabs2.Alliance = {
    cont : null,
    alliancemembers:[],
    number:0,
    totalmembers:0,
    error:false,

    getContent : function (){
        var t = Tabs2.Alliance;
        return t.cont;
    },
    init : function (){
        var t = Tabs2.Alliance;
        t.cont = document.createElement('div');
        return t.cont;
    },
    show : function (){
        var t = Tabs2.Alliance;
        t.cont.style.overflowY = 'auto';
        t.cont.style.maxHeight = '500px';
        t.totalmembers=0;
        t.alliancemembers=[];
        unsafeWindow.getdetails = t.getMemberDetails;

         var m =  '<DIV  class=pdxStat>'+culang.allianceHead+'</div><sup><span  class=boldRed>'+culang.mainImportant+'</span>:</sup>  <span  class="helpText">'+culang.allianceDipHelp+'</span><TABLE  align=center cellpadding=1 cellspacing=0></table>';
         m +='<TABLE class=pdxTab><TD width=200px><INPUT  id=aldiplo type=submit  value="'+culang.buttonShowDiplo+'"></td><TD><b>'+culang.mainSort+'</b>:  <select id="searchAlli"><option  value="name">'+culang.mainName+'</options><option  value="might">'+unsafeWindow.g_js_strings.commonstr.might+'</option><option  value="glory">'+culang.mainGlory+'</option><option  value="login">'+culang.mainLastLogin+'</option><option  value="cities">'+culang.mainCities+'</option><option  value="position">'+culang.mainPosition+'</option><option  value="dip">'+culang.shortDiplo+'</option></select></td><TD><INPUT  id=alList type=submit value="'+culang.mainShow+'"></td><TD  id=progress></td>';
        m+='<TABLE align=center  cellpadding=1 cellspacing=0></table><TABLE id=alOverviewTab  class=alTab><TR align="center"></tr></table>';

        t.cont.innerHTML = m;
        ById('alList').addEventListener('click', function(){
            if (!t.searching){
                t.totalmembers=0;
                t.alliancemembers=[];
                ById('alOverviewTab').innerHTML ="";
                ById('progress').innerHTML ="";
                ById('progress').innerHTML = culang.allianceSearching;
                ById('alList').disabled = true;
                t.error=false;
                t.fetchAllianceMemberPage();
            }
        }, false);
        ById('searchAlli').addEventListener('click', function(){
            if (t.alliancemembers!="") {
                ById('alOverviewTab').innerHTML ="";
                t.paintMembers();
            }
        }, false);
        ById('aldiplo').addEventListener('click', function(){t.paintDiplomacy();}, false);

        window.addEventListener('unload', t.onUnload, false);
    },

    paintMembers: function(){
        var t = Tabs2.Alliance;
        if (ById('searchAlli').value == "name") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=a.Name.toLowerCase(), sortB=b.Name.toLowerCase()
                if (sortA < sortB)
                    return -1
                if (sortA > sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "might") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=parseInt(a.Might),sortB=parseInt(b.Might)
                if (sortA > sortB)
                    return -1
                if (sortA < sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "glory") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=parseInt(a.glory),sortB=parseInt(b.glory)
                if (sortA > sortB)
                    return -1
                if (sortA < sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "login") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=a.LastLogin,sortB=b.LastLogin
                if (sortA < sortB)
                    return -1
                if (sortA > sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "cities") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=a.Cities,sortB=b.Cities
                if (sortA < sortB)
                    return -1
                if (sortA > sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "dip") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=a.dip,sortB=b.dip
                if (sortA < sortB)
                    return -1
                if (sortA > sortB)
                    return 1
                return 0
            });
        }
        if (ById('searchAlli').value == "position") {
            var sortmembers = t.alliancemembers.sort(function(a, b){
                var sortA=a.Position,sortB=b.Position
                if (sortA < sortB)
                    return -1
                if (sortA > sortB)
                    return 1
                return 0
            });
        }
        for (var y = (sortmembers.length-1); y >=0; y--) {
              t._addTab(sortmembers[y].Name,sortmembers[y].Might,sortmembers[y].LastLogin,sortmembers[y].Position,sortmembers[y].dip,sortmembers[y].uid,sortmembers[y].fbuid,sortmembers[y].Cities,sortmembers[y].avatarurl,sortmembers[y].glory,sortmembers[y].dateJoined);
            t.cont.style.overflowY = 'auto';
        }
        t._addTabHeader();
    },

    _addTab: function(Name,Might,LastLogin,Position,dip,uid,fbuid,Cities,avatar,glory,arrive){
        var t = Tabs2.Alliance;
        var row = ById('alOverviewTab').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML ='<img width=25 src="'+ avatar +'">';
         row.insertCell(1).innerHTML ='<A target="_tab"  href="http://www.facebook.com/profile.php?id='+ fbuid  +'">'+culang.mainProfile+'</a>';
        row.insertCell(2).innerHTML = Name;
        var cell2 = row.insertCell(3);
        cell2.width = "60" ;
        cell2.align = "right" ;
        cell2.vAlign = "top";
        cell2.innerHTML = addCommas(Might);
        var cell2 = row.insertCell(4);
        cell2.width = "60" ;
        cell2.align = "right" ;
        cell2.vAlign = "top";
        cell2.innerHTML = addCommas(glory);
        row.insertCell(5).innerHTML = Cities;
        row.insertCell(6).innerHTML = officerId2String (Position);
        row.insertCell(7).innerHTML = dip;
        row.insertCell(8).innerHTML = LastLogin;
        row.insertCell(9).innerHTML = arrive;
    },

    _addTabHeader: function() {
        var t = Tabs2.Alliance;
        var row = ById('alOverviewTab').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "<u><b>"+culang.mainAvatar+"</b></u>";
        row.insertCell(1).innerHTML = "<u><b>"+culang.mainFacebook+"</b></u>";
        row.insertCell(2).innerHTML = "<u><b>"+culang.mainName+"</b></u>";
        row.insertCell(3).innerHTML = "<u><b>"+unsafeWindow.g_js_strings.commonstr.might+"</b></u>";
        row.insertCell(4).innerHTML = "<u><b>"+culang.mainGlory+"</b></u>";
        row.insertCell(5).innerHTML = "<u><b>"+culang.mainCities+"</b></u>";
        row.insertCell(6).innerHTML = "<u><b>"+culang.shortPos+"</b></u>";
        row.insertCell(7).innerHTML = "<u><b>"+culang.shortDiplo+"</b></u>";
        row.insertCell(8).innerHTML = "<u><b>"+culang.mainLastLogin+"</b></u>";
        row.insertCell(9).innerHTML = "<u><b>"+culang.mainCreate+"</b></u>";
    },

    paintDiplomacy : function () {
        var allianceName = '';
        var membersCount = '';
        ById('alOverviewTab').innerHTML ='';

         var m = '<CENTER><TABLE class=xtab><TR><TD  valign=top><TABLE class=xtab><TR><TD colspan=2  style=\'background: #33CC66;\'  align=center><B>'+culang.allianceFriendly+'</B></TD></TR>';
         m += ((Seed.allianceDiplomacies[''+culang.kocFriendly+''] ==  null)?'<TR><TD  colspan=2>'+culang.allianceNoFriendly+'</TD></TR>':'<TR><TD><B>'+unsafeWindow.g_js_strings.commonstr.alliance+'</B></TD><TD><B>'+culang.mainPlayer+'</B></TD></TR>');
        for (k in Seed.allianceDiplomacies[''+culang.kocFriendly+'']){
            allianceName = Seed.allianceDiplomacies[''+culang.kocFriendly+''][k]['allianceName'];
            membersCount = parseInt(Seed.allianceDiplomacies[''+culang.kocFriendly+''][k]['membersCount']);
            if (membersCount > 0)
                 m += '<TR><TD>' + allianceName +  '</TD><TD align=right>' + membersCount +  '</TD></TR>';
        }
        m +=  '</TABLE></TD><TD valign=top><TABLE  class=xtab><TR><TD colspan=2 style=\'background: #FF6633;\'  align=center><B>'+culang.allianceSetFriendly+'</B></TD></TR>';
         m += ((Seed.allianceDiplomacies['friendlyToThem'] ==  null)?'<TR><TD  colspan=2>'+culang.allianceFriendlySet+'</TD></TR>':'<TR><TD><B>'+unsafeWindow.g_js_strings.commonstr.alliance+'   </B></TD><TD><B>'+culang.mainPlayer+'</B></TD></TR>');
        for (k in Seed.allianceDiplomacies['friendlyToThem']){
            allianceName = Seed.allianceDiplomacies['friendlyToThem'][k]['allianceName'];
            membersCount = parseInt(Seed.allianceDiplomacies['friendlyToThem'][k]['membersCount']);
            if (membersCount > 0)
                 m += '<TR><TD>' + allianceName +  '</TD><TD align=right>' + membersCount +  '</TD></TR>';
        }
        m += '<TR><TD  colspan=2 style=\'background: #FF6633;\'  align=center><B>'+culang.allianceFriendlyToYourAlliance+'</B></TD></TR>';
         m += ((Seed.allianceDiplomacies['friendlyToYou'] ==  null)?'<TR><TD  colspan=2>'+culang.allianceFriendlySet+'</TD></TR>':'<TR><TD><B>'+unsafeWindow.g_js_strings.commonstr.alliance+'</B></TD><TD><B>'+culang.mainPlayer+'</B></TD></TR>');
        for (k in Seed.allianceDiplomacies['friendlyToYou']){
            allianceName = Seed.allianceDiplomacies['friendlyToYou'][k]['allianceName'];
            membersCount = parseInt(Seed.allianceDiplomacies['friendlyToYou'][k]['membersCount']);
            if (membersCount > 0)
                 m += '<TR><TD>' + allianceName +  '</TD><TD align=right>' + membersCount +  '</TD></TR>';
        }
        m +=  '</TABLE></TD><TD valign=top><TABLE  class=xtab><TR><TD colspan=2 style=\'background: #CC0033;\'  align=center><B>'+culang.allianceHostile+':</B></TD></TR>';
         m += ((Seed.allianceDiplomacies['hostile'] ==  null)?'<TR><TD  colspan=2><b>'+culang.allianceNoHostile+'</b></TD></TR>':'<TR><TD><B>'+unsafeWindow.g_js_strings.commonstr.alliance+'</B></TD><TD><B>'+culang.mainPlayer+'</B></TD></TR>');
        for (k in Seed.allianceDiplomacies['hostile']){
            allianceName = Seed.allianceDiplomacies['hostile'][k]['allianceName'];
            membersCount = parseInt(Seed.allianceDiplomacies['hostile'][k]['membersCount']);
            if (membersCount > 0)
                 m += '<TR><TD>' + allianceName +  '</TD><TD align=right>' + membersCount +  '</TD></TR>';
        }
        m += '</TABLE></TD></TR></TABLE></CENTER>';
        ById('alOverviewTab').innerHTML = m;
    },


    fetchAllianceMemberPage : function () {
        var t = Tabs2.Alliance;
        ById('alList').disabled = true;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pf = 0;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetInfo.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                t.totalmembers = (rslt["allianceInfo"]["members"]);
                for (var i=1;i<=10;i++) {
                    params.pageNo = i;
                    params.pf = 0;
                    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + unsafeWindow.g_ajaxsuffix, {
                        method: "post",
                        parameters: params,
                        onSuccess: function (transport) {
                            var info = eval("(" + transport.responseText + ")");
                            if (info.ok) {
                                for (var k in info["memberInfo"]){
                                    if ( info["memberInfo"][k]["might"] != undefined && !t.error){
                                        t.alliancemembers.push ({
                                            Name: info["memberInfo"][k]["name"],
                                            Might: info["memberInfo"][k]["might"],
                                            Cities: info["memberInfo"][k]["cities"],
                                            Position : info["memberInfo"][k]["positionType"],
                                            dip : info["memberInfo"][k]["daysInPosition"],
                                            LastLogin : info["memberInfo"][k]["lastLogin"],
                                            uid : info["memberInfo"][k]["userId"],
                                            fbuid : info["memberInfo"][k]["fbuid"],
                                            avatarurl : info["memberInfo"][k]["avatarurl"],
                                            glory : info["memberInfo"][k]["glory"],
                                            dateJoined : info["memberInfo"][k]["dateJoined"],
                                        });
                                    }
                                    ById('alOverviewTab').innerHTML ="";
                                    t.paintMembers();
                                }
                                 if (!t.error) ById('progress').innerHTML    = '(' + (t.alliancemembers.length) +' '+culang.mainFrom+' '+  t.totalmembers +')';
                                if ( t.alliancemembers.length >= t.totalmembers) ById('alList').disabled = false;
                            } else  if (info.error) {
                                ById('alList').disabled = false;
                                ById('progress').innerHTML = ""+culang.mainError+"!";
                                t.error=true;
                            }
                        },
                        onFailure: function (rslt) {;
                            notify ({errorMsg:'AJAX error'});
                        },

                    });
                }
            },
            onFailure: function (rslt) {;
                notify ({errorMsg:'AJAX error'});
            },
        });
    },

    hide : function (){
    },
};
/************************************************************************************
*                        KOC POWER - TABS LANGUAGE                                    *
************************************************************************************
 Tabs.Language = {
 tabOrder : 800,                    // order to place tab in top bar
 tabLabel : 'Language',            // label to show in main window tabs
 myDiv : null,
 language : {needTranslation:{}},
 link  :  {"http://koc-power-bot.googlecode.com/svn/trunk/translation/translation_en.js":"en","http://koc-power-bot.googlecode.com/svn/trunk/translation/translation_de.js":"de"},

 init : function (div){    // called once, upon script startup
 var t = Tabs.Language;
 t.myDiv = div;
 var m = "<DIV class=pdxStat>"+translate("Language Settings")+"</div><TABLE><TR>\
 <TD>"+translate("Set Language")+" : "+ htmlSelector({en:"en",de:"de"},Options.language,"id=pblang_type") +"</td>\
 <TD><input  id=pblang_update value='"+translate("Save Settings")+"' type=submit  DISABLED /><span id=pblang_msg  ></span></td></tr>\
 <TR><TD>"+translate("Language files download")+" : "+ htmlSelector(t.link,null,"id=pblang_link") +"</td>\
 <td><input id=pblang_download value='"+translate("Download")+"' type=submit /></td></tr>\
 <TR><TD>Show current language array: </td>\
 <TD><input id=pblang_show value='"+translate("Show")+"' type=submit /></td></tr>";
 t.myDiv.innerHTML = m;

 document.getElementById("pblang_type").addEventListener('change', function (){
 if(Options.language != document.getElementById("pblang_type").value)
 document.getElementById("pblang_update").disabled = false;
 else
 document.getElementById("pblang_update").disabled = true;
 },false);
 document.getElementById("pblang_update").addEventListener('click', function (){
 var language = document.getElementById("pblang_type").value;
 var s = GM_getValue ("Language_"+language);
 if (s != null){
 var lang = JSON2.parse (s);
 t.sendMessage("Loaded <b>"+language+"</b> Version <b>"+lang.Version+"</b>");
 Options.language = document.getElementById("pblang_type").value;
 } else {
 t.sendMessage("<span  class=boldRed> Language <b>"+language+"</b> not found.  Please download language file!</span>");
 document.getElementById("pblang_type").value = Options.language;
 }
 },false);
 document.getElementById("pblang_download").addEventListener('click', function (){
 document.getElementById("pblang_download").disabled = true;
 GM_xmlhttpRequest({
 method: 'GET',
 url: document.getElementById("pblang_link").value,
 onload: function(xpr) {t.updatelanguage(xpr.responseText, document.getElementById("pblang_link").value);},
 onerror: function(xpr) {t.updatelanguage(xpr.responseText, false);}
 });
 },false);
 document.getElementById("pblang_show").addEventListener('click', function(){
 t.showlanguage();
 },false);
 },

 hide : function (){         // called whenever the main window is hidden, or another tab is selected
 var t = Tabs.Language;
 },

 show : function (){

 },

 showlanguage : function(){
 var t = Tabs.Language;
 t.poplangshow = new CPopup('pbShowLanguage', 10, 10, 400, 500, true, function() {t.popshowlang.destroy();});
 t.poplangshow.getTopDiv().innerHTML = '<TD><B>Language Array:</td>';
 t.poplangshow.getMainDiv().innerHTML  = '<DIV style="overflow-y:auto"><TABLE align=center  cellpadding=0 cellspacing=0 width=100% class="pdxTab"  id="pblang_showarray"></table><div id=pblang_status  ></div></div>';
 t.paintlanguagearray();
 t.poplangshow.show(true);
 },

 paintlanguagearray : function(){
 var t = Tabs.Language;
 var m = '';
 for (var k in t.language.needTranslation){
 m  += "<TR><TD>"+k+": </td><TD><input  id='pblang_"+k+"'  value='"+(t.language.needTranslation[k]==1?'':t.language.needTranslation[k])+"'  /></td></tr>";
 }
 for (var k in t.language){
 if(k != "needTranslation")
 m += "<TR><TD>"+k+": </td><TD>"+t.language[k]+"</td></tr>";
 }
 document.getElementById("pblang_showarray").innerHTML = m;
 document.getElementById("pblang_status").innerHTML  = "<center><input type=submit id=pblang_statussave value=Save  /><input type=submit id=pblang_statusexport value='Export new  translation' /></center>";
 document.getElementById("pblang_statussave").addEventListener('click', function(){
 for (var k in t.language.needTranslation){
 var j = document.getElementById("pblang_"+k).value;
 if(j != '')
 t.language.needTranslation[k] = j;
 }
 saveLanguage();
 },false);
 document.getElementById("pblang_statusexport").addEventListener('click', function(){
 t.export();
 },false);
 },

 export : function(){
 var t = Tabs.Language;
 var pop = new CPopup('pbExportLanguage', 0, 0, 400, 400, true, function() {this.destroy();});
 var m = "<textarea rows=15 cols=50 >";
 for (var k in t.language.needTranslation){
 if(t.language.needTranslation[k] != 1)
 m += "\""+k+"\":\""+t.language.needTranslation[k]+"\",\n";
 }
 m += "</textarea>";
 pop.getMainDiv().innerHTML = m;
 pop.show(true);
 },

 sendMessage : function (msg){
 document.getElementById("pblang_msg").innerHTML = msg;
 },

 updatelanguage : function(result, response){
 var t = Tabs.Language;
 if(!response) {
 t.sendMessage("<span class=boldRed>Error loading file. Try again later</span>");
 document.getElementById("pblang_download").disabled = false;
 return;
 }
 var rslt = null;
 try{
 rslt = JSON2.parse(result);
 } catch (e){
 t.sendMessage("<span class=boldRed>Error reading file. Please notify devs</span>");
 logit(inspect(e,7,1));
 document.getElementById("pblang_download").disabled = false;
 return;
 }
 var s = GM_getValue ("Language_"+rslt.curlang);
 if (s != null){
 var lang = JSON2.parse (s);
 for (k in rslt){
 if(lang.needTranslation)
 if(lang.needTranslation[k]) //Remove from array if already translated
 delete lang.needTranslation[k];
 lang[k] = rslt[k];
 }
 } else {
 var lang = rslt;
 }
 setTimeout (function (){GM_setValue ('Language_'+rslt.curlang, JSON2.stringify(lang));}, 0);
 t.sendMessage("Successfully loaded language file. Please refresh");
 document.getElementById("pblang_download").disabled = false;
 },
 }

 function readLanguage () {
 var t = Tabs.Language;
 if(!Options.language) return;
 var s = GM_getValue ("Language_"+Options.language);
 if (s != null){
 var lang = JSON2.parse (s);
 for (k in lang){
 t.language[k] = lang[k];
 }
 }
 t.language.curlang = Options.language;
 }

 function saveLanguage (){
 var t = Tabs.Language;
 setTimeout (function (){GM_setValue ('Language_'+t.language.curlang, JSON2.stringify(t.language));}, 0);
 }

 function translate (str) {
 var t = Tabs.Language;
 if(t.language[str])
 return t.language[str];
 else {
 if(t.language.needTranslation[str] == undefined)
 t.language.needTranslation[str] = 1;
 else if (t.language.needTranslation[str] != 1)
 return t.language.needTranslation[str];
 }
 return str;
 }
*/
